Dev Pratap Singh

Designing for 1 Million AI Agent Tasks a Day: Building Crashproof

AI Engineering and System Design 25 min

An experiment in durable execution, fair scheduling, and what happens when workers fail at the worst possible moment.

A million tasks a day is only about 11.6 tasks per second.

That's the first thing I noticed when I sat down to design an AI agent execution platform. The API throughput wasn't particularly intimidating. But then I started thinking about what happens after a task gets accepted.

Say an agent has been running for 29 minutes. It has fetched documents, processed them, and finally called a payment API. The payment goes through, but the worker crashes before saving the response. Another worker picks up the task. Does it start from scratch? Does it make the payment again? How does it even know what the previous worker managed to finish?

I've dealt with similar problems while working on backend and payment systems. I wanted to take those ideas beyond a system design diagram and actually build the infrastructure, kill processes, introduce failures, and see what happened.

That's how I ended up building Crashproof, a durable execution engine using Python, PostgreSQL and RabbitMQ that runs locally on my Mac.

So far, I've tested crash recovery across three execution attempts with just one committed mock-provider operation, compared scheduling policies across 10,000 small tenants and one noisy tenant, and completed a 360-task smoke test. The million-task/day workload is the design target, not a throughput result I've already achieved. The current engine runs synthetic workflows rather than actual LLM agents.

In this post, I'll go through the design, why I made certain decisions, what actually happens to a task from submission to completion, and where the implementation still falls short of the scale I'm targeting.

1. Understanding the scale

Let's start with the numbers.

1,000,000 / (24 × 60 × 60) = 11.57 tasks/second

Even if I assume a peak of five times the average, that is about 58 new tasks per second. The submission endpoint isn't necessarily the difficult part. The amount of work already in progress is.

A task might spend two seconds making a request, two minutes processing documents, or half an hour executing a workflow. Little's Law gives a useful starting point: L = λ × W, where L is the mean number of items in a system, λ is the throughput and W is the mean time spent there. The measurement boundaries have to match.

For an illustrative workload, I assumed the following distribution. These are design assumptions, not measurements from Crashproof.

Task classFraction of arrivalsTime holding a slotActive slots at 5× peak
Short90%2 s104
Medium9%120 s625
Long1%1,800 s1,042
Total100%30.6 s weighted mean1,771

Screenshot 2026 11 28 at 2.55.35 AM

Look at the last row of the breakdown. Just 1% of arrivals account for roughly 59% of the occupied slots. If I aim for 70% utilization, the simple model calls for about 2,530 provisioned slots at that peak.

A slot isn't necessarily a CPU core. It could be a coroutine waiting for an LLM response, a browser session holding hundreds of megabytes of memory, or a dedicated process running code. If every task consumed one second of actual CPU time, the same peak would require around 97 equivalent CPU cores at 60% CPU utilization. Memory, provider limits and queue latency would need their own estimates.

This is the capacity model I started with, not a benchmark of my Mac. It also explains why I wanted to focus on the execution engine rather than just optimizing the submission API.

2. Designing the architecture

I kept the distributed implementation in Python. There is also an earlier SQLite reference engine in the repository, which is useful for running small experiments without starting a broker. The distributed path is the one I'll focus on here.

Screenshot 2026 11 28 at 2.56.51 AM

The stack runs locally with Docker Compose. PostgreSQL stores the durable execution state. RabbitMQ transports dispatch messages. A scheduler decides which tenant gets to run next, and a separate reaper recovers work whose ownership has expired. The mock external provider has its own SQLite database, so committing an external effect and updating my execution engine are genuinely separate transactions.

The default Compose setup starts four worker processes. I didn't need Kubernetes or a paid cloud account to reproduce these coordination failures.

One design decision I made early on was to keep PostgreSQL as the source of truth, rather than RabbitMQ. The message carries enough information to attempt a claim, and a worker checks the database before doing anything with it.

The execution path, at a high level, looks like this:

Client → API → PostgreSQL (QUEUED)
                    ↓
              Fair scheduler
                    ↓
          DISPATCHED + outbox
                    ↓
                RabbitMQ
                    ↓
         Worker claims the run
                    ↓
        Checkpoints / tool calls
                    ↓
               Terminal state

I'll go through each part in order. First, these are the five tables that make the whole thing work:

TableWhat it contains
tenantsTenant identity, concurrency allowance, weight and scheduling/token-bucket state
runsRequest, status, current step, attempts, deadline, lease and generation
outboxDispatches that still need to reach RabbitMQ
eventsAn ordered record of important run transitions
effectsStable identities and outcomes for external operations

The way I think about it now is simple: the run is permanent state, a message tells a worker there's something to do, and the worker itself is disposable.

3. Following a task through the system

3.1 Accepting a run

Here's a request the current API accepts:

curl -s http://127.0.0.1:8080/v1/runs \
  -H 'Authorization: Bearer demo-token' \
  -H 'Idempotency-Key: first-run' \
  -H 'Content-Type: application/json' \
  -d '{"query":"demo","steps":[
    {"type":"sleep","duration_ms":200},
    {"type":"fake_api"}
  ]}'

There are three step types: sleep to simulate waiting, cpu to simulate compute, and fake_api to exercise an external effect. A request can contain up to 20 steps. It can also specify a priority, a deadline of up to 1,800 seconds (including queue time), and an attempt limit.

The API locks the corresponding tenant row in a short transaction, checks whether the idempotency key already exists, applies admission limits, and inserts the run with status QUEUED. A newly created run returns HTTP 202; an identical retry returns HTTP 200 with the existing run ID. The uniqueness constraint is scoped to the tenant and the key. The payload is hashed so that reusing a key with different input is rejected (HTTP 400 in this implementation).

Why bother with this before even starting execution? Imagine the insert commits, but the API connection dies before the client receives the response. From the client's perspective, the request failed. From the database's perspective, the run exists. Retrying with the same key resolves that uncertainty without creating another run.

The status, result, events and effects can all be inspected through tenant-scoped HTTP endpoints. The event endpoint returns a JSON history, not a live SSE stream.

3.2 Fair scheduling: the noisy-neighbor problem

Once a run is accepted, I don't publish it immediately to a global FIFO queue. The scheduler first decides which tenant is eligible for capacity.

Imagine one organization submits a thousand tasks, and then a thousand smaller organizations submit one task each. If all of them go through a single FIFO admission policy, the smaller organizations sit behind the original backlog. Adding more workers helps drain it, but doesn't change the underlying allocation policy.

The current scheduler uses a weighted virtual-finish value for each tenant. It selects an eligible tenant with the smallest value, chooses that tenant's highest-priority available run, and advances the tenant's value by 1 / weight. An idle tenant's value is rebased against the minimum among active tenants when it becomes active again, so it doesn't accumulate unlimited advantage just by being idle.

For equal-cost tasks, weights of one and two should give the second tenant roughly twice the dispatch opportunity while both are continuously eligible. I say dispatch opportunity deliberately: a 30-minute task costs much more than a two-second task, and this implementation doesn't account for that difference yet. It is not DRR or a full resource-aware fair scheduler.

The scheduler uses a short transaction to lock an eligible tenant and run, reserve a concurrency slot by changing the run to DISPATCHED, increase its generation, update the virtual-finish value, and insert an outbox row. FOR UPDATE SKIP LOCKED helps competing scheduler processes avoid waiting behind rows another transaction holds. The intended reservation policy counts both dispatched and running jobs against the tenant's concurrency limit.

I also tested the scheduling order with 10,000 small tenants, each with one run, plus one noisy tenant with 1,000 runs inserted ahead of them. I asked the actual PostgreSQL scheduler to make 100 dispatch decisions, then calculated what FIFO would have selected from the same arrival sequence.

Screenshot 2026 11 28 at 2.57.24 AM

The weighted scheduler selected 99 small-tenant runs and one noisy-tenant run. The calculated FIFO baseline selected 100 noisy-tenant runs. The scheduler took 4.322 seconds to make those 100 decisions in that run, which is around 23 decisions per second. That is a useful baseline, but it also highlights a potential bottleneck: the modeled peak of 58 new runs per second is higher than the dispatch rate observed in this particular large-tenant experiment.

This experiment does not measure actual waiting-time percentiles or worker execution, and FIFO was calculated rather than run as a second engine. The raw result and experiment script are in the repository. The next step is to measure both policies under real arrivals, different weights and mixed execution durations.

3.3 Dispatching work without losing it

At this point the scheduler knows which run should execute. It still needs to get that decision to a worker, and this is where the first dual-write problem shows up.

If the scheduler updates a run to DISPATCHED and crashes before publishing, a worker might never hear about that run. Reversing the operations just creates the opposite problem: the broker could contain a message for a state transition that didn't commit.

I used a transactional outbox. The scheduler changes the run's state and writes the corresponding dispatch intent in the same PostgreSQL transaction. A separate relay reads pending outbox entries and publishes persistent messages to RabbitMQ with publisher confirms. Only after publication does it mark the outbox row delivered.

PostgreSQL transaction
    reserve run + advance generation
    insert outbox(run_id, generation)
COMMIT

Outbox relay
    publish(run_id, generation)
    wait for broker confirmation
    mark outbox delivered

There is still a failure window. The broker can accept a message and the relay can crash before the database records that acceptance. A retry can publish the message a second time. Rather than trying to eliminate every duplicate at the transport layer, I made the consumer tolerate duplicate dispatches.

There is also a trade-off in the current implementation: the relay holds database locks while publishing and waiting for confirmation. This keeps the prototype straightforward, but I would avoid holding a transaction open across slow network I/O in a higher-throughput version. I'd investigate short relay claims, explicit retry state and batched confirms.

3.4 Claiming a run atomically

The message contains a run ID and a generation. A worker can only move that run from DISPATCHED to RUNNING if the generation still matches, the lease is valid and the run hasn't been cancelled.

In simplified SQL (using named parameters for readability):

UPDATE runs
SET status = 'RUNNING',
    attempt = attempt + 1,
    lease_until = clock_timestamp() + interval '15 seconds'
WHERE id = :run_id
  AND status = 'DISPATCHED'
  AND generation = :generation
  AND lease_until > clock_timestamp()
  AND NOT cancelled
RETURNING *;

If two workers receive the same message, both cannot successfully make that same conditional state transition. The second can see that the run is no longer in the state it expects.

In this implementation, the worker acknowledges the RabbitMQ dispatch after the durable database claim, rather than after the whole workflow finishes. That means RabbitMQ does not have to retain an unacknowledged delivery throughout a long execution. It also means I have deliberately moved responsibility for recovering claimed work into PostgreSQL and the reaper. Without that recovery path, acknowledging early would be unsafe.

The worker fetches messages one at a time and runs a claimed job in a thread while continuing to service the AMQP connection. A worker process currently handles one run at a time; this is not an asynchronous worker implementation with hundreds of resident coroutines.

4. Making execution survive failures

4.1 Leases, heartbeats and zombie workers

A permanent claim would make it easy to get stuck. A worker could claim a run, crash, and leave the run marked RUNNING forever.

Instead, a dispatch or running job has a lease. The standard Compose configuration uses a 15-second lease. During synthetic execution, the worker periodically makes a guarded checkpoint call; this also renews its lease. A reaper scans for expired or timed-out runs and either returns them to the admission queue or chooses a terminal outcome according to cancellation, deadlines and the attempt limit.

The next scheduler dispatch increments the generation.

Generation 1 → Worker A claims the run
                 Worker A stops responding
                 Lease expires
Generation 2 → Worker B claims the run
                 Worker A wakes up

This is the subtle part: a lease expiring doesn't mean Worker A is dead. It may have been paused, or its connection to the database may have failed. It could still attempt to write a result.

That is why every checkpoint and completion validates the current generation and the unexpired lease in a short database transaction. An old generation can't simply overwrite the state belonging to a newer one. This is the idea behind fencing tokens.

I like this explanation by Martin Kleppmann: the protected resource needs to reject requests from obsolete owners. A lock that expires without such a check doesn't stop an old process from doing work.

In Crashproof, the protected resource is the authoritative database state. It doesn't follow that an old worker is physically incapable of executing an external HTTP request. That needs a different mechanism.

4.2 Picking up where the previous worker left off

The engine executes an ordered list of steps, with the next unfinished step recorded in the database. When a step finishes, the worker updates that position and writes a corresponding event. A new attempt starts from the recorded position rather than replaying the entire workflow.

Step 0: complete
Step 1: complete
Step 2: running   ← worker dies
Step 3: pending

Replacement begins from Step 2.

For the synthetic CPU and sleep operations, intermediate lease renewals do not record the internal computation or elapsed wait as resumable state. A crash during a long step repeats that unfinished step. This isn't instruction-level recovery, nor is it a general-purpose deterministic workflow-replay engine like Temporal.

The distinction matters for a real 30-minute task. If its entire computation is one activity and I haven't persisted progress inside it, I may lose almost 30 minutes of work. Splitting expensive work into appropriately sized checkpoints, or adding activity-specific checkpoint artifacts, trades persistence overhead for recovery time.

4.3 The hardest part: external side effects

Consider a financial workflow. The worker calls a payment API, the provider commits the payment, and then the connection breaks. When a replacement starts, the local database still doesn't know whether the transfer happened.

A database transaction on my side can't roll back the provider's database. A fencing token can protect my local result, but it can't make an arbitrary payment API reject an obsolete worker's request.

To explore this, I implemented a small HTTP provider that performs a synthetic publish operation. It stores its operations in an independent SQLite database. The provider can be configured to deliberately close the HTTP connection after the first successful commit.

Each effect gets a stable key derived from the run and step:

run_id:step:step_index

The engine records an INTENT in its effect ledger before making the request. The provider receives that key in the idempotency header. On the provider side, a transaction checks whether the key already exists; an identical retry receives the saved receipt rather than creating a second operation. A changed payload for the same key is rejected. Back in the engine, the worker stores the confirmed receipt only while it still has valid ownership.

Notice that the key doesn't contain the attempt number or generation. Those can change three times, ten times, or more, but it's still the same intended operation.

Here is the failure sequence I wanted to test:

Worker records operation intent
Worker sends HTTP request
Provider commits operation in its own database
Provider drops the response
Worker sees an error and retries later
Next attempt sends the same operation key
Provider returns the already committed receipt

The second request is not evidence of a second external effect. In this particular provider, the unique operation key is what prevents that.

If a run reaches a failed, timed-out or cancelled outcome while an effect remains an unconfirmed intent, the engine marks it NEEDS_RECONCILIATION. It doesn't automatically reconcile or compensate arbitrary third-party actions yet. For an API without suitable idempotency or lookup semantics, there is no general way to distinguish a lost request from a lost response, and blindly retrying a financial operation would be the wrong decision.

4.4 Putting it to the test: three attempts, one effect

The distributed integration experiment runs real PostgreSQL, RabbitMQ and independent processes. It starts four workers, submits a three-step workflow (a 100 ms wait, a five-second wait and a mock API call), waits until the first checkpoint, then kills the worker that owns it. The experiment configures a shorter two-second lease to make recovery easy to observe, and enables the provider's response-loss behavior.

The event history from the recorded run makes the recovery visible:

Screenshot 2026 11 28 at 2.58.03 AM

The first attempt claimed the run about a second after acceptance and recorded checkpoint 1. After the worker kill, the reaper returned the run to the queue at about 3.36 seconds. Generation 2 claimed it and finished the five-second step. The mock provider dropped the first response, so this attempt failed and became eligible for retry. Generation 3 claimed it, obtained the existing receipt and completed the run.

Recorded outcomeValue
Final run stateSUCCEEDED
Claims / execution attempts3
Lease recovery events1
Rows committed in the provider's operation ledger1
Time from accepted event to completed event~9.31 s
Total reported experiment duration26.233 s

The two time measurements are deliberately separate: the full experiment also includes setup and its additional test work. The exact kill and provider-commit timestamps aren't individual entries in the run event log, so the plot uses the recorded checkpoint and failed-attempt events as boundaries rather than inventing those timestamps.

The test independently opens the mock provider's database and asserts that it contains exactly one operation. It also checks the engine's effect ledger and the final run status. The complete JSON result contains the original timestamps.

This was the experiment I wanted to get working the most. The worker recovery and the lost-response retry happened in the same run, and the provider's database still contained just one operation. That is evidence for the mock provider's idempotency contract, not a guarantee for an arbitrary banking API.

4.5 Retries, cancellation and backpressure

The current failure handler chooses between requeueing the run, failing it, timing it out, cancelling it or marking it for reconciliation. Retries use a capped exponential delay with randomized jitter. The available_at field keeps a retry ineligible until its delay expires; a worker doesn't need to sleep through the entire backoff period. The implementation catches execution exceptions broadly, so more precise transient/permanent failure classification is still needed.

Cancellation is also persistent state. Queued or dispatched runs can be cancelled directly; running jobs observe the cancellation flag at a guarded checkpoint. In the current code, the flag doesn't necessarily interrupt an external call that's already in flight. If the action has committed, cancellation doesn't undo it.

There are two separate overload controls. The API has a per-tenant token bucket, defaulting to 100 new requests per second with a burst capacity of 1,000. An identical idempotent retry doesn't consume another token. It also limits a tenant's combined queued, dispatched and running backlog (the default MAX_QUEUE is 10,000 per tenant). Rate-limit violations produce HTTP 429; reaching the backlog limit produces HTTP 503.

Then the scheduler applies the tenant's active-run concurrency allowance. These controls address different problems. Someone may have permission to submit 100 requests per second but only run four jobs simultaneously. Without a backlog limit, the queue could still grow until the work becomes useless.

In a full AI platform I'd add limits on token consumption, cost, provider requests, browser sessions and physical execution resources. Retrying an LLM request isn't necessarily free, and adding more workers won't fix a provider that's already rate-limiting the system.

5. Benchmarks: what the engine actually handles

So how fast is it right now? There are two recorded workloads worth looking at: a burst of 100 synthetic HTTP submissions in the integration test, and a 30-second Compose smoke test at 12 submissions per second, reported in the README.

Screenshot 2026 11 28 at 2.58.44 AM

ExperimentResult
Burst submission100 accepted, zero submission errors
Burst submission interval0.53 s (reported admission rate: 189.57/s)
Burst completion audit100 succeeded, zero pending, 12.91 s total
Short open-loop test6 of 6 succeeded at target 2/s over 3 s; no dropped iterations
Compose smoke test360 of 360 completed at target 12/s for 30 s (reported in README)
24-hour soakNot run

The number I don't want to overinterpret here is 189.57/s. That's how quickly the API accepted the burst, not how quickly the workers completed it. Multiplying that number by 86,400 would tell us very little about sustainable throughput. The small burst's entire submit-and-audit duration was 12.91 seconds. Even that completion figure includes the test harness and isn't a steady-state capacity measurement.

The sustained benchmark script runs an open-loop submission schedule, counts dropped iterations and errors, journals accepted run IDs, then audits their terminal states. This is more informative than reporting only HTTP success, because an API can continue returning 202 while its execution queue grows indefinitely.

5.1 Testing the million-task target

The next benchmark I want to run is a 15-minute workload at 12/s, followed by a longer soak, a peak workload and mixed-duration tasks. At 12/s for 24 hours, the target is 1,036,800 submissions. To claim one million completed tasks per day, I need the actual terminal counts and elapsed time, not just the configured arrival rate. I also need to distinguish completion within the 24-hour window from completion during a subsequent drain period.

For a million-run audit, I'd change the current per-run HTTP polling approach to a scalable batched audit, retaining the raw IDs and terminal outcomes. Otherwise the test harness itself could become a large part of the database and API workload. I would also report CPU, RAM, storage, queue-age distribution, task mix, dropped iterations, hardware configuration and multiple trials. The short recorded results do not establish those properties.

6. Scaling toward 1 million tasks/day

I don't think this requires a completely different architecture at the outset. I would keep the same separation between durable run state, scheduling, dispatch and replaceable execution, and improve the parts that become bottlenecks under measurement.

The scheduler

The first thing I'd look at is the scheduler. The current query examines eligible tenants and their outstanding work, and the relay publishes one outbox record per transaction. The fairness experiment's dispatch rate is a good reason to profile these paths before promising the modeled peak. Maintaining an indexed ready-tenant set, batching reservations and relay publication, and eventually partitioning scheduler ownership by tenant would reduce work on the hot path. Global resource limits would still need coordination across partitions.

PostgreSQL and checkpoint overhead

Next comes PostgreSQL. A worker currently renews its lease through a checkpoint call roughly every 200 ms during a synthetic wait or CPU step. At 1,771 resident executions, that cadence alone implies roughly 8,855 renewal calls per second if all are in that kind of step. Each call has database work and the current code opens a connection for database operations. That's a modeled upper-pressure example, not a measured write rate. I'd separate heartbeat timing from step checkpoints, use a connection pool, and measure contention before increasing worker counts. Event retention and archival matter as well: 20 one-KiB history events per run at a million runs/day would be about 19 GiB of logical event data every day, before indexes and WAL.

Execution pools and actual agents

For actual agents, I would split workers by resource class. Network-bound LLM calls suit an async worker pool; document processing needs CPU capacity; browser and untrusted code sessions need stronger isolation. Fairness would move from counting dispatches to accounting for the resource consumption of activities. Long waits for callbacks or approval should become durable waiting states that release execution resources. Crashproof doesn't implement those suspension semantics today.

I would also separate the agent loop from external tool authorization. A real agent would persist model decisions and tool-call identities before executing consequential actions. Model output is nondeterministic; restarting a crashed agent by asking the model what to do again can produce an entirely different sequence of effects. That's why completed tool calls and approved actions need their own durable state, independent of the model's context.

Custom orchestration vs. a workflow engine

Eventually I would compare this implementation with a durable workflow engine such as Temporal. Building leases, recovery and checkpoints myself was useful for learning, but maintaining deterministic replay, timers, workflow versioning and dynamic activity graphs is an entirely different level of responsibility. I'd rather delegate mature orchestration mechanisms where they fit than keep rebuilding them indefinitely.

Where the prototype falls short

There are a few things I wouldn't be comfortable claiming about the engine yet. The current version is a local laboratory with static demo credentials, no production TLS/authentication setup, and no arbitrary-code sandbox. It doesn't run a real LLM, doesn't provide multi-AZ durability, and hasn't demonstrated a million completed tasks in a day. Prometheus and Grafana are available through a Compose profile, but metrics and tracing coverage are still limited.

I would not expose it to the public internet or connect it to real consequential APIs as-is. The provider adapter currently expects a particular mock-compatible contract, not the idempotency and reconciliation semantics of every third-party service.

There are further correctness tests I want to expand: concurrent schedulers racing near the tenant limit, stale workers and network partitions across separate hosts, broker restart during dispatch, cancellation races around provider effects, and failure recovery during database failover. A local passing experiment is evidence for the scenarios it exercised, not a proof that every failure is handled.

7. Running Crashproof locally

The project is MIT licensed. To run the distributed prototype locally with Docker Compose:

git clone https://github.com/Devps2003/crashproof-agent-engine.git
cd crashproof-agent-engine
make up-distributed

The API is available at http://127.0.0.1:8080. Run the sample request from earlier in the article, then replace RUN_ID with the returned ID:

curl -s http://127.0.0.1:8080/v1/runs/RUN_ID/events \
  -H 'Authorization: Bearer demo-token'

To start the local observability profile:

make observe-distributed

For a sustained benchmark against the running API:

python3 benchmarks/sustained.py --rate 12 --duration 900

The full soak command is available as make bench-soak. It takes at least 24 hours and has not been run yet. The distributed fault-injection script and fairness experiment require explicitly configured disposable databases and, for the former, RabbitMQ. The distributed design notes describe how to run them. Some tests truncate application tables; don't point them at data you care about. The make chaos-* commands exercise the separate SQLite reference engine, not the distributed path.

To stop the distributed services:

make down-distributed

8. What I took away from building this

When I started, I thought most of the complexity would be in the queue and the worker pool. The queue turned out to be one of the simpler parts.

The difficult decisions were deciding when work had been accepted, who was allowed to change its state, what happened when that authority expired, and whether an operation outside my database had already happened. Once I separated a logical run, its physical attempts and its external effects, the reasons for leases, fencing tokens, the outbox and idempotency became much clearer.

Those mechanisms aren't specific to AI agents. They show up in payment processing, background jobs and distributed workflows too. Agents just make the problems more apparent: their execution is longer, their decisions can change, and their tools can have real consequences.

The code and the recorded experiments are here: github.com/Devps2003/crashproof-agent-engine. I'll be using it to explore the parts of agent infrastructure that are easy to miss when all you see is a successful model response.


References: Repository and quickstart · Distributed implementation · Database schema · Mock provider · Benchmark harness · Recorded integration results · Recorded scheduling results.

Comments

No comments yet.