GuideAI AgentsAI Infrastructure

Running an AI agent on a 4-core VPS: what it costs and what breaks

A practical guide. Every command below was run on the system described in the prerequisites, and the date it was last checked is in the line above.

A practical build for an agent that survives real traffic on rented hardware — systemd units, locking, idempotent publishing and the numbers from a month of production runs.

Most "run an AI agent" tutorials assume the model is the hard part. On rented hardware the model is an API call; the hard part is everything around it. This guide is the build we actually run: an agent that drafts and publishes articles on a 4-core, 8 GB VPS, unattended, with a human checking the output rather than driving it.

The numbers below come from that system over 30 days of production, not from a benchmark harness. Where a figure is an estimate, it says so.

What the machine actually does

The workload is small and bursty. Over one month it made 977 model calls, moved 1.25 million input tokens and 765 thousand output tokens, and produced 63 published articles across 140 scheduled runs. Total model spend at list prices was about three dollars.

That shape — a few minutes of work every few hours, mostly waiting on an HTTP response — is what makes a cheap VPS viable. The process that serves the website peaks at 217 MB of resident memory under normal traffic. The agent itself is idle between runs. Nothing on the box needs a GPU, and nothing needs more than two cores at once.

If your agent instead does local inference, this guide is the wrong template: a 4-core CPU-only box generates a few dozen tokens per second at best, which is fine for a background job and far too slow for interactive use. The measured numbers for that case are in the Labs section.

The five failure modes that cost the most time

These are ordered by how often they appeared in our logs, not by how interesting they are.

  1. The agent runs twice and does the work twice. A timer fires while the previous run is still waiting on a slow model call. Two processes pick up the same queue item and publish the same article with two different slugs.
  2. A write succeeds and the reply is lost. The publish call times out; the retry creates a second article because nothing checked whether the first one landed.
  3. A half-finished job stays half-finished. The draft exists, the cover does not, and the queue row now looks "in progress" forever.
  4. The model returns something the next stage cannot read. Not invalid JSON in the clean case — an empty field, a value outside an enum, or a plausible number where the text said nothing.
  5. A restart loses the run's state. The job was at step three of five; after a deploy it starts again at step one and pays for the tokens twice.

Each of these has a specific, boring fix. None of them is a smarter prompt.

Structure: one timer, one lock, one row per unit of work

The agent runs as a systemd oneshot unit triggered by a timer, not as a long-lived daemon. That single decision removes a class of bugs: there is no in-memory queue to lose on restart, and a crashed run leaves the system in a known state rather than half-alive.

[Unit]
Description=newsroom agent (one cycle)
After=network-online.target

[Service]
Type=oneshot
User=agent
WorkingDirectory=/srv/newsroom
EnvironmentFile=/srv/newsroom/.env
ExecStart=/srv/newsroom/.venv/bin/python -m agent cycle --count 1 --live
TimeoutStartSec=1800
Nice=10
MemoryMax=1200M

[Install]
WantedBy=multi-user.target

Three details matter more than they look:

  • `TimeoutStartSec` must exceed your slowest legitimate run. Ours is 1800 seconds because one run took 1020 seconds when an image provider stalled. A shorter timeout kills the process mid-publish and leaves the lock held.
  • `MemoryMax` turns a memory leak into a failed unit instead of an OOM kill that takes the web server with it. The unit restarts; the site does not notice.
  • `Nice=10` keeps a burst of tokenising from competing with the request handlers on a shared 4-core box.

The lock is a row in the database, not a file, and it carries an expiry:

BEGIN IMMEDIATE;
INSERT INTO run_lock(name, owner, expires_at)
  VALUES ('cycle', :run_id, datetime('now', '+45 minutes'))
  ON CONFLICT(name) DO UPDATE
    SET owner = excluded.owner, expires_at = excluded.expires_at
    WHERE run_lock.expires_at < datetime('now');

The WHERE on the update is the whole trick: a second run either takes an expired lock (the previous owner died) or fails to take a live one and exits. A lock without an expiry means one crash stops the pipeline until a human notices — which is how a "self-healing" system quietly stops publishing for three days.

Idempotency: derive the key from the content, not from the attempt

The CMS this pipeline writes to has no idempotency header. The guarantee comes from a unique field instead: the slug.

Before creating anything, look the slug up. If it exists, use that document. If the create call times out, look the slug up again before retrying — a 504 after a successful write is the case that produces duplicates, and it is not rare on a busy afternoon.

hit = find_by_slug(slug)
if hit:
    return hit, created=False
try:
    return post("/api/articles", doc), True
except TransportError as e:
    if e.status in (500, 502, 503, 504) or e.timed_out:
        hit = find_by_slug(slug)     # the write may have landed
        if hit:
            return hit, False
    raise

Slugs are derived from the title, so a retry of the same story computes the same key. That is the property that makes the whole approach work: idempotency here is a consequence of the key being a function of the content.

Checkpoints: record the step, not just the outcome

A publish is three writes: the media object, the article that references it, and the verification read. If the process dies after the second one, a naive retry uploads a second cover and creates a second article.

Store the stage on the row:

published_stage: 'media_created' -> 'article_created' -> 'verified'

The resume path reads that column and skips what is already done. It also stores the remote media id, so the article can be re-attached rather than re-uploaded.

The same idea covers the draft: our rows carry the model's raw text, the fact-check output and the editorial verdict, so a revision loop resumes with the previous draft and the specific complaints instead of regenerating from the source.

Verification: a 200 is not a publication

The single most expensive bug in a publishing pipeline is a document that exists but is not visible. Two variants bit us:

  • The status field. The CMS expects _status; an unknown key is ignored, the document is stored as a draft, and the API still answers 200. From the agent's side the publish succeeded.
  • The public URL. The article is published but the page 404s, because the slug in the URL and the slug in the document disagree on a trailing character.

So the last step is a read-back with three assertions: the document exists, its title matches what was sent, and the public URL answers 200.

verify = cms.get(doc_id)
assert verify["title"].strip() == title.strip()
assert verify["_status"] == "published"
assert http.get(public_url).status == 200

That check costs one request and catches the whole class.

What it costs, measured

From 30 days of logs, on the same box that serves the site:

  • 140 runs, 63 published pieces, median run 116 seconds, longest 1,020 seconds.
  • 977 model calls, 1.25 M input tokens, 765 k output tokens.
  • About $3.00 at list prices — roughly five cents per published article.
  • 124 stories researched against 74 published: most candidates are rejected by the gates, and that rejection is the system working.

The token bill is not what makes this expensive. The editorial layer is: deciding what to write, checking whether it is true, and reading the result. A pipeline that optimises tokens and ignores that will save cents and waste days.

The parts we would not repeat

  • Running the CMS and the agent on the same box is fine at this size and a bad idea at the next one. A runaway agent can starve Postgres; MemoryMax and Nice are mitigations, not a design.
  • Polling a queue table every few minutes is simple and adequate for a handful of jobs per day. Above a few thousand, it becomes the bottleneck.
  • Storing raw model output in the database made debugging possible and made the database large. If you do it, decide retention on day one.

Sources

Related

Keep reading

All guides →
PreviousUSC AIHub: A University-Hosted Generative AI Stack Benchmarked on Four H100sNextReliability patterns that keep retries from doubling the bill

Comments

0 comments

Sign in to join the discussion, or create an account.

No comments yet

Be the first to say something useful.