# How do queues schedule millions of delayed retries?

By Vishal Kumar · Published 2026-11-09 · Updated 2026-11-13
Source: https://fungyaan.com/p/delayed-retries
Tags: data-structures, queues, postgres, reliability, go

**The verdict, which the measurements below will earn:** three structures do almost all of it.
- **A min-heap ordered by due time** is exact and simple, and is what most timer libraries use.
- **A timing wheel** (a circular array of time slots) makes adding, cancelling and firing O(1). It's what Netty, Kafka and the Linux kernel use when there are millions of timers, at the price of firing on tick boundaries.
- **A database row with an index on `next_attempt_at`**, polled by workers, is what you want when the retry must **survive a restart**. Outboxes and Postgres-backed job queues work this way.

In memory, a well-sized timing wheel fired a million timers about 16× more cheaply than a heap. The database handled 10,000 due jobs a second with a 1 ms median lateness, and fell behind at 50,000.

"Do this later" sounds like the simplest request a program can make, and a surprising amount of engineering hides behind it. Picture a million of those promises in flight at once: retries, timeouts, reminders, each due at a different moment. Each of these three structures is a different answer to the same small question at the heart of the case: what's due next?

The code is in [systems-data-structures](https://github.com/the-vishal-kumar/systems-data-structures) (`timers/`, `cmd/timerdemo`, `cmd/dbqueue`).

> **Case file**
>
> | | |
> |---|---|
> | **The case** | "Retry this in 30 seconds", a million times over |
> | **Suspects** | Min-heap, timing wheel, database row + index |
> | **Culprit** | The wrong structure for how many timers, and whether they must survive a restart |
> | **The fix** | Runtime timers or a wheel in memory, an indexed row when it must survive |
> | **Evidence** | Go, `cmd/timerdemo` and `cmd/dbqueue`, PostgreSQL 17 with 4 workers |

## The suspects at a glance

| | Min-heap | Timing wheel | Database row + index |
|---|---|---|---|
| **Add** | O(log n) | O(1) | An `INSERT` (or `UPDATE`) and an index entry |
| **Cancel** | O(log n), if you track the position | O(1) | An `UPDATE` or `DELETE` |
| **Fire** | O(log n) per timer | O(1) per timer, plus one slot visited per tick | A poll query: `… WHERE next_attempt_at <= now() … FOR UPDATE SKIP LOCKED` |
| **Precision** | Exact | One tick (e.g. 1 ms, 100 ms) | The polling interval |
| **Survives a restart** | No | No | **Yes** |
| **Shared by many workers** | No (per process) | No (per process) | **Yes** |
| **Used by** | Go's runtime timers, most language timer libraries | Netty's `HashedWheelTimer`, Kafka's purgatory (hierarchical wheels), the Linux kernel | Transactional outboxes, Postgres job queues, the email outbox of the blogging platform I run |

## The first clue: heap vs timing wheel, in memory

The timing wheel comes from George Varghese and Tony Lauck's work in 1987. The idea is plain, and lovely for it: instead of sorting timers, put each one where the clock hand will be when it's due. A timing wheel is an array of slots, one per tick. A timer due in *d* ticks goes into slot `(now + d) mod size`. If *d* is longer than one turn of the wheel, the timer also stores how many full turns to wait. Each tick, the wheel visits one slot: it fires the timers on their last turn and counts the others down.

I scheduled timers due anywhere in the next 60 seconds, on a simulated 1 ms clock, cancelled half of them (most retries become unnecessary when the first attempt eventually succeeds), and ran the clock until the rest had fired:

| Timers | Structure | Add | Cancel | Clock + fire, per timer fired | Memory added |
|---:|---|---:|---:|---:|---:|
| 100,000 | Min-heap | 49 ns | 55 ns | 286 ns | 1.0 MB |
| 100,000 | Wheel, 512 slots (~117 turns per minute) | 27 ns | 15 ns | 150 ns | 1.2 MB |
| 100,000 | Wheel, 65,536 slots (one turn) | 64 ns | 21 ns | **42 ns** | 0.9 MB |
| 1,000,000 | Min-heap | 56 ns | 114 ns | 701 ns | 9.1 MB |
| 1,000,000 | Wheel, 512 slots (~117 turns) | 24 ns | 20 ns | **757 ns** | 9.4 MB |
| 1,000,000 | Wheel, 65,536 slots (one turn) | 47 ns | 84 ns | **44 ns** | 11.5 MB |

```mermaid
xychart-beta
  title "Clock + fire per timer fired, 1,000,000 timers (ns)"
  x-axis ["Min-heap", "Wheel, 512 slots", "Wheel, 65,536 slots"]
  y-axis "ns per timer" 0 --> 757
  bar [701 , 757 , 44]
```

All three fired every remaining timer exactly once, at its tick, with none fired after cancellation (a test checks this).

What the evidence says:

- **A wheel sized to cover the delay range in one turn is the fastest by far:** 44 ns per timer fired, against 701 ns for the heap at a million. The heap's cost grows with log n *and* with cache misses as it gets bigger; the wheel's per-timer cost stayed flat.
- **A small wheel with long delays can be worse than a heap.** This is the twist that keeps the wheel from being an easy answer. With 512 slots and a 60-second range, each timer is visited about 117 times before it fires (once per turn), and at a million timers that cost more than the heap. That's why **hierarchical** wheels exist: Kafka layers wheels with coarser ticks (milliseconds, then seconds, then minutes) and moves timers down a level as they get close.
- **Cancellation is where wheels shine for retries and timeouts.** Most of these timers never fire: the request finishes, the retry isn't needed. O(1) cancel matters more than fast firing.
- **The trade:** a wheel fires on tick boundaries. With a 100 ms tick (Netty's default), a timer can fire up to 100 ms late. For retries and timeouts, that's fine.

## The second clue: a row and an index, for timers that must survive

Now for the humble suspect. In-memory timers die with the process. If "retry this email in 10 minutes" must survive a deploy or a crash, the retry is a **row**:

```sql
CREATE TABLE jobs (id bigint PRIMARY KEY, run_at timestamptz NOT NULL, done_at timestamptz, attempts int NOT NULL DEFAULT 0);
CREATE INDEX jobs_due ON jobs (run_at) WHERE done_at IS NULL;   -- only pending jobs in the index

-- each worker, in a loop: claim a batch, and lease it so a crashed worker's batch comes back
WITH due AS (
  SELECT id FROM jobs WHERE done_at IS NULL AND run_at <= now()
  ORDER BY run_at LIMIT 100 FOR UPDATE SKIP LOCKED)
UPDATE jobs j SET run_at = now() + interval '10 minutes', attempts = j.attempts + 1
FROM due WHERE j.id = due.id
RETURNING j.id;
```

The partial index keeps only pending jobs, so it stays small as finished jobs accumulate. `SKIP LOCKED` lets several workers poll without blocking or double-claiming each other. Pushing `run_at` forward as a lease means a worker that dies mid-batch doesn't lose the jobs: they come due again in 10 minutes. Success sets `done_at`; failure sets `run_at` to the backoff time. One query claims, leases and recovers, with no extra coordinator. I find that economy genuinely beautiful.

Measured on PostgreSQL 17 with 4 workers, 10% of attempts failing and retried 1 s later:

| Jobs, due over 20 s | Poll interval when idle | Handed out (peak second) | Lateness p50 | p99 | max |
|---:|---|---:|---:|---:|---:|
| 200,000 (10,000/s) | 50 ms | 11,280/s | 1 ms | 13 ms | 51 ms |
| 200,000 (10,000/s) | 500 ms | 11,823/s | 8 ms | 114 ms | 485 ms |
| 1,000,000 (50,000/s) | 50 ms | 40,400/s | **6.2 s** | 13.0 s | 13.1 s |

- **While the workers keep up, the polling interval sets the lateness:** a job due just after a poll that found nothing waits for the next one. A short interval costs a cheap index probe per worker per interval. To avoid polling when idle, add `LISTEN/NOTIFY` as a wake-up signal.
- **At 50,000 due per second, this setup fell behind**, and jobs ran seconds late. Each claim is an `UPDATE` with index maintenance and WAL. Bigger batches and more workers help up to a point. Beyond that, the database is the wrong place for the timer itself, and that's where a dedicated queue earns its keep. For example, SQS's per-message `DelaySeconds` (up to 15 minutes as of Nov 2026; the [SQS, SNS or EventBridge post](/p/sqs-sns-eventbridge) compares the options), or a scheduler in front of Kafka.

## The reveal: two questions decide it

Which one to reach for depends mostly on two questions: how many timers, and must they survive a restart? Here are four situations.

```mermaid
flowchart TD
  A{"Must it survive a restart?"} -->|yes| B["A row with an index on the due time, claimed with SKIP LOCKED"]
  A -->|no| C{"Hundreds of thousands of timers, mostly cancelled?"}
  C -->|yes| D["Timing wheel, sized to fire within one turn"]
  C -->|no| E["The runtime's timers (a min-heap)"]
  F{"Does anything need to happen at expiry?"} -->|no| G["No timer: check on read, sweep in the background"]
```

## Case 1: email retries with backoff

**Situation:** sending an email fails (a provider timeout, a rate limit), and you retry after 1 minute, then 5, then 30, up to a limit. Losing a retry means a lost email.

**What I'd use:** the database row. A few retries a second is nothing for PostgreSQL. The retry is committed in the same transaction as whatever caused the email, and it survives deploys. The email outbox in the blogging platform I run works this way (the [notification system post](/p/design-notification-system) shows where it fits): a partial index on `next_attempt_at`, `SKIP LOCKED` claims, a 10-minute lease, and a cap of 8 attempts.

## Case 2: request timeouts in a busy server

**Situation:** a proxy or RPC server with 100,000 requests in flight, each needing a timeout. Almost all complete before their timeout and are cancelled.

**What I'd use:** an in-memory **timing wheel** (or your runtime's timers, which are usually good enough). Nothing needs to survive a restart, because the requests die with the process. Cancellation dominates, so O(1) cancel is the feature. That's exactly why Netty and Kafka built wheels.

## Case 3: sessions and cache entries that expire

**Situation:** millions of sessions, each expiring at a different time.

**What I'd use:** often no timer at all. That's a satisfying twist: the best timer is sometimes the one you never set. Store the expiry time, check it when the item is read, and sweep in the background. Redis does both: a key with a TTL is deleted when it's accessed after expiry, and a background cycle samples keys with TTLs and deletes the expired ones. A database can do the same with `WHERE expires_at > now()` on reads and a periodic `DELETE`. A timer per item is only needed if something must *happen* at expiry.

## Case 4: "send this reminder in three days"

**Situation:** long delays (hours to weeks), modest volume, and they must survive anything.

**What I'd use:** the database row, with a coarse poll (every few seconds is plenty). Most managed queues can't hold a message that long (SQS delays max out at 15 minutes), and in-memory timers obviously can't. Put an index on the due time, claim with `SKIP LOCKED`, and make the action idempotent: a retried claim after a crash can run it twice.

> **Remember this**
> - Two questions decide it: how many timers, and must they survive a restart?
> - Cancellation dominates retries and timeouts: a timing wheel cancels in O(1).
> - A timer that must survive is a row: partial index, `SKIP LOCKED`, a lease.

## What to do on Monday

1. **Must it survive a restart?** Then it's a row (or a durable queue's delayed message), not an in-memory timer.
2. **In memory, start with the runtime's timers.** Reach for a timing wheel when you have hundreds of thousands of timers and most get cancelled. Size the wheel (or use levels) so most timers fire within one turn.
3. **In the database:**
   - a partial index on the due time;
   - claim with `SKIP LOCKED` and a lease;
   - batch the claims;
   - poll at an interval that matches the lateness you can accept;
   - make the job idempotent.
4. **Measure lateness** (handed out minus due), not only throughput. It's the first number to move when the workers fall behind.

Next time you write "retry in 30 seconds", spare a thought for the heap, the wheel or the indexed row keeping that promise. Each is a small piece of good design that has done this work reliably for decades. For where these retries live in a real system, the [notification system post](/p/design-notification-system) is the next case to read.

*Measured Nov 2026 on a laptop (Intel i7-8550U) with Go 1.27 and PostgreSQL 17.11. In-memory timers run on a simulated clock, so their numbers are CPU only; database numbers are real time with 4 workers on the same machine. Code and full results: [systems-data-structures](https://github.com/the-vishal-kumar/systems-data-structures).*
