Failure drills for an AI backend
Simulate timeouts, invalid output, worker restarts and disconnects and prove the system degrades cleanly.
By Invicly Tech, , in FastAPI with Python for AI Backends. About 11 minutes to read.
In short
A failure drill breaks one dependency on purpose, such as a slow model, bad JSON from the model, a crashed worker or a browser that leaves mid-stream, and checks that the system fails cleanly. Local stubs make each drill repeatable and free. The evidence you look for is a stable error response, a job that finishes or retries, released resources and a trace that explains what happened.
Think of it like this: A failure drill is a fire drill for software: you ring the alarm on a quiet day so that the real one is boring.
Explained simply
Every part of an AI backend will fail at some point. The model provider gets slow, the model returns broken JSON, a worker container restarts during a deploy, and users close the browser tab while an answer is still streaming. A failure drill is a test where you cause one of these on purpose and watch what happens.
You do this locally, with stubs. A stub is a tiny fake that behaves badly on demand: a provider that waits 30 seconds, or one that returns text that is not valid JSON. Because the stub is yours, the failure happens the same way every time, and it costs nothing.
Before each drill, write down what should happen. For a slow provider, maybe a 504 error with the code provider_timeout after 20 seconds. Then run the drill and compare. If the result is a raw 500 with a stack trace, you found a bug before your users did.
Look at more than the HTTP response. Check that the job in the database ends as done or failed, not stuck in running. Check that connections were closed. Check that the trace and logs tell the story clearly enough for someone woken up at night to understand it.
Press Play on a diagram to walk through it one step at a time.
- Slow provider
- Deadline fires
- 504 or retryable error code
- No stuck connections
- Invalid model output
- Schema validation fails
- Bounded retry or safe error
- No bad data stored
- Worker restart
- Job is not lost
- Retry is idempotent
- Status ends done or failed
- Browser disconnect
- Stream stops
- Upstream call cancelled
- Usage still recorded
- 1Pick one failure
Slow, invalid, crash or disconnect
- 2Write the expected outcome
Error code, job state, trace
- 3Inject with a stub
Local, repeatable, free
- 4Collect evidence
Response, database, logs, trace
- 5Fix and turn into a test
So it stays fixed
- Back to step 1
In depth
Drill 1: a slow or hanging provider
Give every outbound model call a deadline. With HTTPX you can set httpx.Timeout on the client for connect, read, write and pool waits; for a whole operation, wrap it in asyncio.timeout (Python 3.11 and later) or asyncio.wait_for. To drill it, swap the provider for a stub that sleeps longer than the deadline, or use httpx.MockTransport with a handler that raises httpx.ReadTimeout.
Expected evidence: the route returns your stable error, for example 504 with code provider_timeout and a request ID, within the deadline plus a small margin. If you retry, the logs show a bounded number of attempts with backoff. The trace shows the model span ending in an error status. Nothing is left waiting: the connection pool has free slots afterwards, which you can check by running the drill several times in a row without a slowdown.
- Deadline on every outbound call
- Bounded retries with jitter, only for retryable errors
- Stable error code clients can act on
- Repeat the drill to spot leaked connections
Drill 2: invalid model output
If the service asks the model for JSON, sooner or later it will get something else: a sentence, a cut-off object or a field with the wrong type. Your code should parse it with a Pydantic model using model_validate_json and catch ValidationError. Then choose a fixed policy: retry once with a reminder about the format, fall back to a plain-text answer without structured fields, or return an error such as 502 with code invalid_model_output.
To drill it, script the stub to return three bad outputs in a row. Expected evidence: no more than the agreed number of attempts, nothing invalid written to the database, a clear error to the client and a log line with the validation error type but not the full model output, which might contain user data.
Drill 3: kill the worker mid-job
Upload a document so an ingestion job starts, then stop the worker hard, for example with docker compose kill worker, while the job is running. Restart it with docker compose up -d worker. A durable design survives this because the job's state lives in the database and queue, not in the worker's memory. The job holds a lease with an expiry time; when the lease runs out, a worker claims it again.
The second attempt must be idempotent. Use the document ID and chunk index as a unique key and insert with ON CONFLICT DO NOTHING, or delete the document's partial chunks before re-inserting. Expected evidence: the job status moves to done, the chunk count matches a clean run and there are no duplicates. If attempts exceed the limit, the job moves to failed and its message lands in the dead-letter queue, where a person can inspect it.
- Queue to Worker A: Deliver job 421Deliver job 42
- Worker A to Database: Lease job 42, status running2Lease job 42, status running
- 3Killed halfway throughWorker A to Worker A: Killed halfway through
- Queue to Worker B: Redeliver after lease expires4Redeliver after lease expires
- Worker B to Database: Upsert chunks (no duplicates)5Upsert chunks (no duplicates)
- Worker B to Database: Status done6Status done
Drill 4: the browser disconnects mid-stream
When a client closes the connection during a StreamingResponse, the server stops sending and the generator producing the stream is cancelled, which raises asyncio.CancelledError at its current await. Your generator should use try and finally to close the upstream model stream, so the provider stops generating tokens. You can also poll await request.is_disconnected() between chunks if your server or proxy does not cancel promptly.
To drill it, start a stream with curl -N against a fake model that emits one token every 200 ms, then press Ctrl+C after a second. Expected evidence: a log line saying the stream was cancelled by the client, the fake model's counter showing it stopped early, usage recorded for the tokens actually produced, and the trace span marked as cancelled rather than as a server error. Do not swallow CancelledError; clean up and let it propagate.
Learn it in 5 short steps
About 35m each. Track them with a timer in your plan.
- 1Stub a slow provider~35m
- 2Return invalid model output~35m
- 3Kill and restart the worker~35m
- 4Disconnect the browser mid-stream~35m
- 5Check errors, jobs and traces~35m
Key points
- Change one thing per drill and write down the expected outcome before you run it.
- Stubs such as httpx.MockTransport or a fake provider with a delay make timeouts repeatable in tests.
- A killed worker must not lose the job: it should be picked up again and processed only once in effect.
- When the client disconnects, cancel the model call so you stop paying for tokens nobody reads.
- Every drill should leave a trace and a log line that a person on call could follow.
Key terms
Tap a card to flip it. 0/5 known
Examples
import asyncio
class SlowProvider:
async def complete(self, prompt: str) -> str:
await asyncio.sleep(30) # simulate a stuck upstream
return "too late"
def test_slow_provider_returns_504(client_with):
client = client_with(provider=SlowProvider(), timeout_s=0.2)
r = client.post("/chat", json={"question": "What is the refund window?"})
assert r.status_code == 504
assert r.json()["error"]["code"] == "provider_timeout"client_with is a project fixture that builds a TestClient with overrides.
Simulating a provider timeout with httpx.MockTransport
Step 1: build the provider's HTTP client with a MockTransport whose handler raises httpx.ReadTimeout. Step 2: inject that client through the dependency your route already uses. Step 3: call POST /chat. Expected evidence: status 504, error code provider_timeout and a request ID in the body; the test runs in milliseconds because no real waiting happens. Cleanup: clear the overrides in the fixture teardown.
import httpx
from app.deps import get_provider_http
def timeout_handler(request: httpx.Request) -> httpx.Response:
raise httpx.ReadTimeout("stubbed", request=request)
def test_timeout_maps_to_504(app, client):
stub = httpx.AsyncClient(transport=httpx.MockTransport(timeout_handler), base_url="https://model.example.com")
app.dependency_overrides[get_provider_http] = lambda: stub
r = client.post("/chat", json={"question": "Refund window?"})
assert r.status_code == 504
body = r.json()["error"]
assert body["code"] == "provider_timeout" and body["request_id"]A streaming generator that cleans up on disconnect
Step 1: open the model stream inside the generator. Step 2: yield each token as an SSE data line. Step 3: in finally, close the upstream stream and record usage, whether the stream ended normally or was cancelled. Drill: start the stream with curl -N, press Ctrl+C, then check the logs for stream_cancelled and a usage row with the partial token count.
import asyncio, logging
log = logging.getLogger("chat")
async def sse_events(model, prompt, usage):
stream = await model.stream(prompt)
produced = 0
try:
async for token in stream:
produced += 1
yield f"event: delta\ndata: {token}\n\n"
except asyncio.CancelledError:
log.info("stream_cancelled", extra={"tokens": produced})
raise
finally:
await stream.aclose()
await usage.record(output_tokens=produced)Quick reference
- One failure per drill; write the expected result before you run it.
- httpx.MockTransport(handler) fakes any HTTP response or exception without a network.
- asyncio.timeout(seconds) (Python 3.11+) bounds a whole async operation.
- docker compose kill worker, then docker compose up -d worker, to drill a crash.
- Idempotent writes: unique key on (document_id, chunk_index) plus ON CONFLICT DO NOTHING.
- On disconnect: close the upstream stream in finally and re-raise CancelledError.
- Evidence = response + job state + logs + trace, not the response alone.
Common mistakes
- Only testing the happy path, then learning in production that a timeout returns a raw 500 with a stack trace.
- Retrying invalid model output forever instead of a small fixed number of times.
- Running drills against shared or production systems instead of a local stack you can reset.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write a FlakyProvider stub whose complete method raises TimeoutError on the first two calls and returns "ok" on the third.
- Exercise 2medium
Write call_with_deadline(coro_fn, seconds) that awaits coro_fn() and raises ProviderTimeout (your own exception) if it takes longer than seconds.
- Exercise 3hard
Write the steps and checks for a worker-restart drill on the local Compose stack, including cleanup.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is this the same as chaos engineering?
- It is the small, local version of the same idea. Chaos engineering runs controlled failures in shared or production-like environments; drills here use stubs on your own machine.
- How often should I run failure drills?
- Turn each drill into an automated test once it passes, so it runs in CI. Repeat the manual ones, such as killing the worker, after big changes to the job system.
- What if my server does not cancel the generator when the client leaves?
- Behaviour depends on the server and any proxy in front of it. Check await request.is_disconnected() between chunks as a backstop and add a total stream deadline.