Pencil sketch on squared notebook paper of an isometric block of square cells bound by a blue strap, with three loose cells arriving along a dashed centre line.

A webhook provider reads any 2xx as delivered and stops retrying. That makes the 201 a promise: once the provider has it, the hook is Ankusa’s to keep. The launch post traces the early version of this problem to a messaging bus outage that cost hooks, and the answer was to journal every hook to disk. Ankusa keeps that rule, but the journal is the node’s own store, and the answer waits until the write has reached the disk.

The cost is the sync. A durable write ends in an fsync, and if every request paid for its own fsync, a node would be limited by how fast the disk can sync one hook at a time. Each request still needs its own answer, but the disk does not need one sync per request. The component that makes that work is the batcher. It lets many callers share one write and one fsync, and it answers each caller only after the sync covering its hook has returned.

This is part 2 of ten on Ankusa’s components. Part 1 covered the edge’s refusals, and the launch post has the overview.

The invariant

The write path is built around one rule: a hook is not acknowledged before it is durable. Two crashes matter here, and the provider’s retry is what connects them.

If the node dies before the sync returns, the provider never received a 201. It treats the missing answer as a failure and retries. Whether the first copy survived the crash is not something the provider can know. If the node dies after the sync returns but before the response leaves, the hook is on disk and the provider still sees a failure. It retries, and unless the source sets a dedupe: key, the retry is stored again as a new hook with a new id. The quickstart says so directly. A repeated delivery after a lost answer is part of the at-least-once contract, and the dedupe key is the setting that collapses it.

Four stages of one request: it arrives, its group is applied without a sync, the fsync returns, and the 201 leaves; a crash before the fsync returns means no 201 and a provider retry, and a crash after it means the hook is stored and the provider retries anyway.

What Ankusa must never do is answer 201 for a hook that is not on disk. The picture below shows where the batcher sits between the edge and the store.

Provider posts to the edge; the batcher group-commits the hook to the local store and the provider gets 201 only after the fsync. Dispatch delivers due rows to sinks, dead-lettering give-ups, and writes bodies too large for a queue message to the blob store as claim packs; the compactor archives hooks to the same blob store as segments.

Callers block in a batcher

The request process does not write to the store. It hands its record to Ankusa.Edge.Batcher.commit/4 and waits for the answer, which comes back as {:committed, env}, {:duplicate, env} or an error. The batcher is one GenServer per partition, and the partition count is part of the node’s configuration. The default is four, as the excerpt below shows. The configuration reference lists the same batcher.* settings with their meanings.

            batcher: %{
              partitions: 4,
              max_batch: 256,
              # commits one partition keeps in flight: a batch is handed to the
              # writer without waiting for the one ahead, so the writer finds every
              # waiting caller in its mailbox and merges them into one group (at 4
              # partitions and 256 closed-loop clients a group is ~130 hooks at 64
              # slots, ~65 at 1, the old one-commit-at-a-time behaviour)
              max_commits: 64,
              # a group is cut at whichever of these two is reached first; every
              # caller in it waits for the whole group, so the byte cap bounds
              # the added ack latency (4 MiB is a few ms of WAL write), and under
              # `wal: :dual` one group is one produce request
              group_commit_max_bytes: 4_194_304,
              group_commit_max_records: 1_024,
              # how long a saturated writer (its last group held 64 or more
              # hooks) waits for the callers it just answered to call again, so
              # they join the next group; 0 disables it. Never at low load.
              group_commit_delay_ms: 1,
              # 0 = commit as soon as the batch fills, no linger: the commit is a
              # Task, so waiting costs a scheduling hop, not head-of-line
              # blocking.
              max_delay_ms: 0,
              # load shedding: a partition refuses (503 overload) once it holds
              # max_queue records, or max_queue_bytes of bodies, counting both
              # the buffer and the batch being committed
              max_queue: 10_000,
              max_queue_bytes: 268_435_456

Three settings shape a partition’s behavior. max_batch caps how many records one commit takes from the buffer, at 256. max_commits caps how many commits a partition keeps in flight, at 64, so a batch is handed to the writer without waiting for the one ahead of it. That matters because it lets the writer find every waiting caller in its mailbox. max_delay_ms is zero by default, which means a batch commits as soon as it fills, with no linger.

The partition also sheds load. Before it buffers a record, it checks the records it already holds, both buffered and in flight, against max_queue (10,000 records) and max_queue_bytes (256 MiB of bodies). A record that would pass either bound is refused at once.

  def handle_call({:enqueue, record, deadline}, from, state) do
    size = record_bytes(record)
    queued = state.count + state.inflight_count
    queued_bytes = state.bytes + state.inflight_bytes

    # A record bigger than the byte bound on its own is still admitted into an
    # empty batcher: `max_body_bytes` is the per-record limit, this one bounds
    # how much a partition holds.
    over_bytes? = queued > 0 and queued_bytes + size > state.max_queue_bytes

    if queued >= state.max_queue or over_bytes? do
      Ankusa.Telemetry.emit([:load_shed], %{queue: queued, bytes: queued_bytes}, %{
        instance: state.instance
      })

      {:reply, {:error, :overload}, state}
    else
      state = %{
        state
        | buffer: [{from, record, deadline} | state.buffer],
          count: state.count + 1,
          bytes: state.bytes + size
      }

      {:noreply, state |> maybe_flush() |> ensure_expiry(from, deadline)}
    end
  end

The bound on bytes has one exception. A record larger than the byte bound is admitted into an empty partition, because max_body_bytes is the per-record limit and this check only bounds how much a partition holds. A refused record never waits. The edge turns the refusal into a 503, which is covered below.

Each record also carries a deadline: the latest moment its batch may start committing. The commit call’s default timeout is 15 seconds (Ankusa.Edge.Batcher.record_deadline_ms/0). A record still sitting in the buffer when its deadline passes is answered {:error, :store_unavailable} and dropped. Once a batch has been cut from the buffer, the writer checks each call’s deadline before it starts the batch, and a batch whose deadline has already passed is refused. A batch that has started is never abandoned: its callers wait for the commit’s outcome, however long the disk takes, so a stall never turns into a 503 for a hook that is then committed.

When a partition cuts a batch, it starts the commit in a supervised task.

  defp start_commit(state) do
    state = cancel_timer(state)
    {_expired, state} = drop_expired(state)

    if state.count == 0 do
      state
    else
      {entries, remainder} = split_batch(state.buffer, state.max_batch)
      records = Enum.map(entries, fn {_from, record, _deadline} -> record end)
      deadline = entries |> Enum.map(fn {_from, _record, deadline} -> deadline end) |> Enum.min()
      instance = state.instance

      task =
        Task.Supervisor.async_nolink(state.task_sup, fn ->
          safe_enqueue(instance, records, deadline)
        end)

The task is started with Task.Supervisor.async_nolink, so it is not linked to the partition. If the task crashes, the partition gets a :DOWN message and answers only the callers of that one batch. Its other buffered callers are unaffected, and the partition keeps running.

One writer, one group, one fsync

Each instance has one Ankusa.Queue.Writer, and it is the only process that assigns sequence numbers. A sequence number is the hook’s position in the queue, and every later stage (dispatch, the compactor, the replay cursors) reads positions that the writer handed out. Because there is one writer, there is one order.

Request processes call the batcher partitions, which pass each batch to a commit task; commit tasks encode delivery rows and prefetch dedupe keys, and the queue writer merges the waiting batches into one group before the store takes it with sync: false.

The group goes to the syncer, which applies it and runs one fsync; the group is then durable, dispatch is woken, and every caller in the group gets its 201.

The writer’s group commit is where the batching happens. It takes the first call it has been handed, then drains every other :enqueue call already sitting in its mailbox, for as long as the group stays within its caps. The caps are group_commit_max_bytes (4 MiB) and group_commit_max_records (1,024). The call that would pass a cap starts the next group. The first call is always taken, however large it is, so a single oversized batch still commits.

  defp group_commit({_from, prepared, _deadline} = first, state) do
    state = state |> begin_group() |> linger()
    {calls, leftover} = drain([first], prepared.count, prepared.bytes, state)

    live =
      Enum.filter(calls, fn {{caller, _tag} = from, _prepared, deadline} ->
        cond do
          expired?(deadline) ->
            GenServer.reply(from, {:error, :deadline_exceeded})
            false

          not Process.alive?(caller) ->
            GenServer.reply(from, {:error, :caller_gone})
            false

          true ->
            true
        end
      end)

    state = if live == [], do: state, else: commit_group(live, state)

    if leftover,
      do: {:noreply, state, {:continue, {:group, leftover}}},
      else: {:noreply, state}
  end

Under saturation the writer waits briefly before it starts a group. A writer whose last group held at least 64 hooks sleeps for group_commit_delay_ms (1 ms by default). The config comment says the wait lets the callers the writer just answered call again and join the next group. At low load there is no wait, because a wait there would only add latency.

The group is applied, not yet synced. The writer applies it with sync: false and hands the replies to Ankusa.Queue.Syncer, a second process whose only job is the fsync. The syncer runs one Ankusa.Store.sync_wal/1 at a time, and each sync covers every group applied so far. While it is syncing group N, the writer is already applying group N+1. The number of fsyncs is therefore bounded by what the disk can do, not by the number of groups.

The syncer’s moduledoc states the visibility rule that makes this safe. A row is not visible to readers, and a reply is not sent, until the sync that covers it has returned. The writer marks the group as applied before the write, so anything that can read the rows during the write sees them as not yet durable. Only the ack latency is pipelined. A hook’s visibility to dispatch and the answer to its retry still wait for the sync.

Sequence diagram of the pipelined fsync: request processes block in a batcher partition, the writer applies group N without syncing and hands its replies to the syncer, the syncer runs one WAL sync while the writer applies group N+1, and the callers in group N get their 201 only after the sync that covers them returns.

What one commit contains

The batch the writer applies is one synced write, and the storage doc’s section on the commit lists what it holds. For each hook in the group:

  • the hook itself, keyed by its seq;
  • one pending delivery row and one due key for each sink the source had when the hook was acked, each due key with its active-tenant marker;
  • an archive obligation, but only while the :storage role is running;
  • the dedupe key and its expiry entry, when the source sets dedupe:;
  • the counter deltas (pending, bytes, archive_pending) for the tenant and for the node;
  • the tenant’s ordinal and the next-ordinal marker, when the tenant is new on the node;
  • the next-seq marker, so a restart knows where to continue.

The delivery rows are written in the same batch as the hook, so the hook carries its destinations with it. The critical review’s G3 section records the finding this addresses: hooks whose source was gone at dispatch time were dropped silently. What dispatch does with those rows is the subject of part 3.

Most of the work in a commit does not need the sequence number, so the batcher’s task does it before the writer ever sees the batch. The task encodes the hook binary and the delivery rows, and it runs one multi_get over the batch’s dedupe keys to prefetch what the store already knows. Only the writer assigns seqs, and only the writer writes.

The same key on two partitions

Two callers can send the same dedupe key at the same moment, and if they land on different partitions, neither partition has committed the key yet. The prefetch cannot settle that by itself, so the writer does it. Before it assigns seqs, it re-validates the prefetched keys against the store and the recently committed keys it remembers. Within the group, the first occurrence in seq order wins. The second one gets 201 with the original hook’s id and "duplicate": true, as the quickstart’s status table lists.

A 201 duplicate is an answer about a key that an earlier group wrote. The writer does not send it until the fsync of whatever group holds the original has returned, unless nothing is unsynced. Otherwise the duplicate answer could describe a hook that a crash then erases.

Backpressure is a 503

A partition that is full refuses the record with {:error, :overload}. The router maps that, and the store’s own refusals, to a 503 with Retry-After: 1. The quickstart’s table lists the 503 cases: overload, store_unavailable, and the intake log refusing under wal.type: dual. Ankusa does not hold the request open, and a refused request stores nothing, so the provider’s retry is the next attempt at the same hook.

A commit can fail for a different reason, the disk. If the store cannot take the write, for example because the volume is full, the commit is logged as store commit of N hook(s) failed, nothing acked, and every caller in the group gets store_unavailable. The writer resumes when space frees. Reopening the store is also rate limited: a store that has to reopen does so at most once every 5 seconds, because a reopen replays the WAL and many writers can fail at once.

A failed fsync is more serious, because the rows are already applied. The syncer fences the queue. It answers every entry it covers, and every one that arrives after, with the error, leaves the durable watermark where it was, and does not sync again. The store is told to reopen (Store.report_write_failure/2), and the writer refuses new work. The writer then deletes, in one synced write, the rows of every group that was never acked, and only then resumes at the seq where it stands. So a hook whose provider was told 503 is never visible to dispatch, and the provider’s retry is the one that gets stored.

The node’s /ready endpoint reports the same condition. When the store is failing, /ready answers 503 with store: "failing" and a reason class for the failure (no_space, io_error, read_only, corruption, and so on), so a load balancer takes the node out of rotation while the writes are refused.

What the store survives

The store is one RocksDB database per instance, under the instance’s data directory. RocksDB has its own write-ahead log, and a process crash does not lose a write that was synced. The loss tests in packages/ankusa/test/ankusa/loss_test.exs cover this: they wait for acknowledgements, kill the node with kill -9, and check that every acked hook is still there after the restart.

Recovery on open has two cases, and they are not the same. A torn record at the very end of the log, the kind a crash mid-write leaves behind, is dropped. The store is opened with wal_recovery_mode: :tolerate_corrupted_tail_records, which is exactly that rule. Damage earlier in the log is different. The store refuses to open and reports the path and the reason. A store that cannot be read is not treated as empty, so the node does not start serving on an empty disk.

When the store opens without a backup configured, the boot log says where it lives and what it promises: [ankusa] store at <path>. Durable to power loss on THIS host only. A synced commit survives a crash of the process and a power loss of the machine. It does not survive the loss of the machine’s disk. The intake log, covered later in this series, is what closes that gap, and backups narrow the window in a later part.

What it does not do

The batcher does not change the single-host boundary. The store, the WAL and the backup all live on one machine, so a host that is lost takes its hooks acked since the last backup with it. The intake log, covered later in this series, is the design for closing that gap. Nothing in the commit path replicates a write to another machine.

The commit path is also not used by every configuration. Under wal.type: none, there is no queue, no batcher and no group commit. Ingest verifies the request, publishes to the source’s sinks inside the request, and answers 201 only once every sink has confirmed. Nothing is committed and no segment is written. The node still runs the store for its quarantine pen, API-managed sources and rate-limit overrides, but the hook path is the sinks’ confirms, and a sink that refuses turns the request into a 503. The delivery doc’s direct mode section describes the trade-off, and it is a different ack from the one in this post.

The full commit path, with the storage formats it writes, is in docs/storage.md.