Back

Built to Survive Overload

By Pablo Fernandez12 min read

On October 29 a deploy took Mailingest, my mail platform, down for 13 minutes. Nothing had crashed. NATS, the message bus, reserves each stream's maximum size up front, and with 4.63 GB of its 5 GB already reserved it refused to grow one stream and create another. Every service asked for those streams at startup, got the refusal back as an error, exited, and restarted into the same refusal.

The bus wasn't down. It was full, and full should mean "wait", not "stop". On the server, the fix was raising the store to 20 GB. The fix in the code took longer, because once I looked, the same reflex was everywhere: a dependency that couldn't answer right now took the whole process with it, or held a client forever, or let memory grow until the container died.

I wrote the requirement down in one sentence the next day: the system shouldn't fall over, it should get a bit slower. Resist overload by slowing down, never by growing without limit. It sounds like the easy option. It isn't, because every way of waiting is a queue, every queue is memory, and a wait with no end is a hang with better manners.

Email already knows how to wait

Mail has an advantage most protocols don't: waiting is built into it. An SMTP reply that starts with a 4 is a transient negative completion: the action didn't happen, the condition is temporary, and the client should try again. And a sender can't just give up on one. The sending strategy in RFC 5321 says mail that can't be sent now "MUST be queued and periodically retried", and that the give-up time generally needs to be at least 4 to 5 days.

So for the mail doors, "slower" has a precise meaning. Every sender on the internet already keeps a queue for me. If I say "later" instead of failing, the message waits in their queue and costs me nothing. The three rules I wrote down all come from that:

  • Brake, don't break: bounded queues, backpressure, and temporary refusals the client retries. SMTP 4xx, IMAP BYE [UNAVAILABLE], HTTP 503 with Retry-After, consumers that stop pulling.
  • Never fall over: no crash, no restart loop, no running out of memory, nothing that grows without limit in memory, on disk or in a queue.
  • Never lose what was accepted: no 250 for a message that isn't stored.

The third rule is what makes the first one safe. A 4xx is only harmless if the sender still has the message, and the sender only keeps it if I never said 250. The two replies that matter most are next to each other in the code:

crates/core/src/smtp.rs
/// The reply, before closing, to a command the database could not serve in time
/// (`mailingest_db::saturated`): RFC 3463 4.3.2, "system not accepting network
/// messages", so the client retries later.
pub const SATURATED: (u16, &str) = (421, "4.3.2 Server busy; try again later");
 
// (doc comment trimmed: S3, Postgres or NATS failing, or a stream at its cap)
pub const DEFERRED: (u16, &str) = (451, "4.3.0 Temporary failure; please retry");

The second number in each reply is an enhanced status code, which tells a sender's logs why: 4.3.2 is a server not accepting mail right now, 4.3.0 a temporary failure of the mail system.

A full door says so

The first thing I changed was the doors. Each protocol door had a cap on connections. At the cap, it accepted the socket and then waited for a free slot, saying nothing. The client hung, the kernel's accept queue filled up behind it, and the door stopped hearing even its own shutdown signal.

Now a full door answers at once, in the words each protocol uses for "busy, come back", and goes back to accepting:

crates/gate/src/lib.rs
/// The protocol's "busy, come back later", for a door named `gate`.
fn busy_line(gate: &str) -> &'static [u8] {
    match gate {
        "imap" => b"* BYE [UNAVAILABLE] Server busy; try again later\r\n",
        "pop3" => b"-ERR [SYS/TEMP] Server busy; try again later\r\n",
        "manage_sieve" => b"BYE (TRYLATER) \"Server busy; try again later\"\r\n",
        // Both SMTP doors, and any other: SMTP's is the most widely understood.
        _ => b"421 4.3.2 Server busy; try again later\r\n",
    }
}

IMAP's UNAVAILABLE, POP3's SYS/TEMP and ManageSieve's TRYLATER are each protocol's own way of saying the failure is temporary. The line is written without waiting, since one line fits in any send buffer, so a flood of refusals can't slow the door down.

The same door had a quieter version of the bug on the other side: a client that stopped reading blocked the server's write forever, holding its slot. Every accepted socket now gets keepalive and, on Linux, a 60-second TCP_USER_TIMEOUT, which bounds every write in every protocol from one place.

The product nobody bounded

The memory problem was a multiplication. Each door capped the size of a message (25 MiB) and capped its number of sessions (5,000 for SMTP). Nothing capped the product: 5,000 sessions each buffering a 25 MiB message is over 120 GiB, in a container with 256 MiB.

The fix is one budget per process for message bytes, 64 MiB by default, which SMTP DATA, BDAT and IMAP APPEND reserve from as they read. When the budget is spent, the session doesn't refuse. It stops reading.

sender ── DATA ──▶ session reserves the next bytes ──▶ room? ── yes ──▶ read on │ no ▼ stop reading the socket (TCP window fills, sender waits) │ within 30 s: room? ── yes ──▶ read on │ no ▼ 452 4.3.1, sender retries later
A session that can't reserve memory stops reading; TCP makes the sender wait, and only after 30 seconds does it get a temporary refusal.

That middle step is the slowing down, and TCP does it for free: when the receiver stops reading, its window fills, and the sender's kernel stops sending. The sender sees a slow server, which is exactly what it has. Only if no room comes within 30 seconds does it get 452 4.3.1, "insufficient system resources", and take the message back to its queue.

I tested it locally, with the release build of the SMTP ingest binary on my Mac against its own Postgres 18, Redis, NATS and LocalStack S3. A Python asyncio client ran EHLO, MAIL, RCPT and DATA in a loop with 100 concurrent connections, sending 2 MB messages for 30 seconds, while a script sampled the process's memory every half second. It wasn't the full production stack (building the image didn't fit on the disk that night), but it was the same binary.

BudgetAccepted (250)Refused (451)Peak RSS
16 MiB1,418068 MiB
2 GiB, in effect none9532,619546 MiB

The second row would have been killed in production: 546 MiB is over twice the container's 256 MiB. It also accepted fewer messages, because with every session pushing at once LocalStack saturated, and a message that can't be stored gets 451. With the budget, sessions waited their turn and nothing was refused.

The budget that deadlocked

The first version of that budget had a bug, and the same test found it. Each message reserved its bytes a slice at a time, as it read them. With 100 messages of 4 MB arriving at once under a 16 MiB budget, each one got a slice, the budget ran out, and every message waited for more room that only another waiting message could free. Two messages got through in 45 seconds.

The fix splits the budget in two pools:

crates/core/src/memory.rs
/// A budget, in two pools. Every message's first MiB comes from `first`, taken
/// whole when it starts: messages that each held a slice and all waited for
/// more would wait for each other forever, which a first version did under a
/// flood of large messages.
// (rest of the comment trimmed: growth past the first MiB, below)
#[derive(Debug, Clone)]
struct Budget {
    first: Arc<Semaphore>,
    rest: Arc<Semaphore>,
    growers: Arc<Semaphore>,
}

Each pool is a Tokio semaphore counted in KiB. With the defaults (64 MiB, and 25 MiB as the largest message) the arithmetic in Budget::new gives this split:

64 MiB per process┌──────────────────────────────┬──────────────────────────────┐│ first: 32 MiB │ rest: 32 MiB ││ each message's first MiB, │ growth past the first MiB, ││ taken whole when it starts │ for 8 growers at most │└──────────────────────────────┴──────────────────────────────┘
The default budget: half for every message's first MiB, half for the few large messages allowed to grow at once.

Most mail is far smaller than a MiB, so most messages never touch the second pool. A large one holds a grower's place while it grows, and if it can't grow within 2 seconds it gives everything back with a 452, so the others can finish. A message can't wait while holding something another waiting message needs. In the same run, 701 messages of 4 MB went through in 45 seconds instead of 2, and a test, a_flood_of_large_messages_finishes_instead_of_deadlocking, keeps it that way.

A stream at its cap

Back to where it started: a NATS stream that is full. Mailingest's streams discard new messages when they reach their cap, so a full stream is a publish that fails. The same local setup, with the MAIL stream capped at 2 MiB, nobody consuming from it, and 200 clients for 60 seconds:

  • 3,779 250s and 1,416 451 4.3.0s. The stream held exactly 3,779 messages afterwards: every 250 was in it, and every message that wasn't got a temporary refusal, so nothing was lost.
  • p50 of 2.2 seconds, p99 of 5.4. Slower, and still answering. Peak memory was 69 MiB.
  • Restarted with an 8 MiB cap, the stream grew in place and took 5,952 more in 15 seconds with no refusals, for a total of 9,731.

That restart is the other half of the incident fix. A stream definition the server won't apply no longer stops a service: it keeps the live definition, logs an error, sets a gauge, and retries in the background with a jittered backoff from 30 seconds to 15 minutes. Run against a 1 GB NATS that couldn't fit the default caps, the service started with 4 streams created and 7 reported missing, and accepted 2,407 messages in 10 seconds from 20 clients. Before, that was a restart loop.

The audit found a nastier relative: one service started without two of the stream caps in its environment, and on every restart it shrank those streams to the default. NATS then deletes the oldest messages to fit, silently, and the next service to start grew them back. Provisioning now only ever grows a stream. Shrinking one is something an operator does on purpose.

HTTP has its own "later"

The HTTP services needed the same idea in HTTP's words: 503 with Retry-After. The API had no limit on requests in flight, each with a body of up to 40 MiB, so under a surge it held every request, its body and a database connection until they all timed out together. Now one layer, shared by every HTTP service, refuses what it can't start:

crates/http/src/shed.rs
pub async fn admit(State(limit): State<InFlight>, request: Request, next: Next) -> Response {
    let Ok(permit) = limit.0.try_acquire_owned() else {
        metrics::counter!("mailingest_http_shed_total").increment(1);
        return overloaded();
    };
    hold(next.run(request).await, permit)
}

The API allows 256 at once by default, and the permit is held until the response body has been sent, since a streamed answer to a slow reader is still work in flight. A refused request costs nothing else: no database, no body read.

The rest of the HTTP work was making slowness read as slowness. The request timeout answered 408, which is the client's fault, and SDKs don't retry a 4xx; now it's a 503 to retry. About 48 places turned an exhausted connection pool into a 500; now the error type spots it and answers 503. And PgBouncer holds a query waiting for a connection for up to 120 seconds by default, then fails it with its own message. That went down to 15 seconds in the infrastructure, and the code learned to read it as what it is:

crates/db/src/pool.rs
/// PgBouncer's own wait counts too: past its `query_wait_timeout` it fails the
/// query with that message, the same saturation one hop further.
pub fn saturated(err: &anyhow::Error) -> bool {
    err.chain().any(|cause| match cause.downcast_ref::<sqlx::Error>() {
        Some(sqlx::Error::PoolTimedOut) => true,
        Some(sqlx::Error::Database(db)) => db.message().contains("query_wait_timeout"),
        _ => false,
    })
}

A saturated database is one function, and every door answers it in its own protocol: a 503, IMAP NO [UNAVAILABLE], POP3 -ERR [SYS/TEMP], SMTP 421 4.3.2.

The one place "later" was wrong

The rule has a mirror image, and it showed up in submission, where a client sends mail out. If the message's row was saved and only the publish to NATS failed, answering 451 made the client retry, under a new id, and the email went out twice. A temporary refusal is only honest if the server really didn't keep anything.

So the answer depends on where it failed. Not stored: 451, and the client keeps it. Stored but not published: the client gets its success, and delivery's sweep for stuck messages picks the email up, at most 15 minutes late. The API had the same duplicate, a 500 after the commit, and now shares the same handover.

Slower is not the same as less

There's a way to slow down that is really a failure. Until today, IMAP FETCH also waited for message memory, and if no room came within 30 seconds it answered the body as NIL. Nothing crashed. But Apple Mail's first sync, which asks for whole messages, showed headers with no bodies.

The changes from today, November 8, close that. A FETCH that asks for a whole message, which is what a client's sync asks for, now streams it: the length and the first 256 KiB first, then the rest by ranged reads as each window is written, so a session holds a few windows and none of the message memory. Any other read holds exactly what it needs, waits as long as it takes, and is never refused. Under a spent budget FETCH gets slower, and every body is still there.

The same day, the other places that held a whole message got the same treatment. POP3's RETR and TOP, and the API's raw download, read a message window by window instead of holding it plus a copy. Outgoing delivery writes DATA a piece at a time instead of building a second, dot-stuffed copy. And temporary messages stopped keeping a copy of their body in Redis: every read streams from object storage, a ranged GET per window. All of this is on Mailingest's main branch.

What slowing down costs

Slowing down still costs something, and some of it I decided to pay on purpose. When the usage stream that feeds billing is down, usage records wait in memory, up to 100,000 records, so mail isn't held up; before, every message waited 30 seconds for it. If the process dies in that window, that usage is gone. I chose mail first.

One wait is still the wrong kind. A service that starts while Redis is down waits for Redis without listening, so the MX accepts no connections until Redis comes back. Senders retry, so nothing is lost, but making Redis lazy in every service is a larger refactor than this change, and it's on the open list with fourteen others.

The pattern underneath every change is the same one SMTP has had since the start. A server that can't do something right now has two honest answers, "done" and "not yet", and the dishonest ones are silence, a crash, and a partial answer dressed as a full one. Each of these changes moved one more failure from those to "not yet". A sender keeps the message and comes back later, and that's the slowdown working.

Related articles

Building APIs with Hono

How I build type-safe APIs with Hono: the router, the Context object, Zod validation, centralized error handling, and end-to-end types shared with the frontend.

More Backend Than a Blog Needs

How pablofr.com is built: three services, Postgres, Meilisearch and Redis, one work queue and a lot of SSE. A personal site over-engineered on purpose.

Skew Protection for Next.js

Every deploy strands open tabs asking for chunks only the old build had. My skew protection for self-hosted Next.js on k3s: a Go router that pins each tab.