Scheduling and capacity

Concurrency Counters Drift When Multiple Writers Update Shared State

Shared mutable state accumulates writers until overlapping operations corrupt the value. A dispatcher, a webhook handler, and a reconciler might each decrement a concurrency hold. Every write looks correct in isolation, but a webhook and a reconciler firing together cause a double-decrement. Locks only serialize the error. The fix is partitioning the state by field group and strictly assigning one authoritative writer per field. When reconciliation is confined to the fields it exclusively owns, it can never corrupt a field governed by another path.

Symptoms

  • A counter in shared scheduler state drifts from reality.
  • Reconciliation runs, corrects the drift, and an hour later the number is wrong again by a similar amount.
  • Nobody can say which code path is wrong, because three different components write to that field. Every one of those writes, read on its own, looks perfectly correct.
  • The misleading observation is suspecting transient network corruption or duplicate carrier delivery when every component is functioning as designed. Each write succeeds and appears defensible in isolation, leaving no error trace in application logs.

What is actually happening

Shared mutable state accumulates writers one commit at a time. A dispatcher routes a call and decrements a capacity hold. A webhook handler receives a room-ended event and clears that same hold. A reconciler repairs the hold when the state looks stale.

Every one of those writes is entirely defensible in isolation. Together, they cause a double-decrement on the exact path where the webhook and the reconciler both fire at the same time. The webhook clears the capacity, and the reconciler also clears it. No type system objects to this, because the types are all correct. A numeric decrement is a mathematically valid operation.

This is not a locking problem. If you wrap the update in a strict database transaction lock, the lock simply serialises the writes. The webhook waits for the reconciler to finish its decrement, and then the webhook applies its own decrement. The mathematical result is still wrong. Serialising conflicting state transitions still produces an invalid final counter.

How to confirm it

  1. Query the event log for the drifting field and group by the actor that wrote it. Expect to see at least two distinct services writing the exact same field within seconds of each other. If you see both webhook_handler and reconciler attributing writes to the same counter, you have this race condition.
  2. Check the write history of the corrupted field against the execution times of your webhook handler and reconciler. Expect to find entries where both the webhook and the reconciler fired against the same state transition. This confirms both code paths attempted to repair or clear the same hold.
  3. Grep the codebase for the update query or document modification that targets this specific field. Expect to find it in more than one file. If three different modules can import the update function, the architecture allows multiple writers by default.

How it works

I partition the state by field group and record, in the file that owns it, the single code path allowed to write each group. Adding a second writer to any group is then a correctness violation with a name. It is not a code-review opinion. The reviewer’s question changes from "is this write correct" to "is this the sole writer".

Reconciliation becomes safe because it is confined to the fields it exclusively owns. It never repairs a field that another writer is authoritative for. For a deeper look at how the reconciler handles state cleanly, see my notes on how the scheduler holds stale capacity.

Where types cannot express the invariant, I enforce it with lint rules. These are custom, developer-invoked architecture assertions. I treat them as structural tests rather than style preferences. Across the 528 test files in my TypeScript and Python suite, these rules run locally. They are not wired into any blocking CI deployment gate. A violation is simply a red mark locally, making the architectural boundary visible before the code is even committed.

The rules enforce strict boundaries. There are no direct wall-clock reads inside the scheduler, no direct queries of the live-session store outside the admission path, and no reaching into admission state from a view layer. To understand how strict admission boundaries protect capacity, see my post on enforcing maximum concurrent SIP calls without race conditions.

This discipline requires per-field write attribution in the event log. I use per-call event-sourced traceability with explicit actor attribution. A drift investigation then starts with "who wrote this" instead of a repository grep. Recording per-field write attribution in the event log ensures a drift investigation starts with identifying the author rather than grepping the codebase.

This approach generalises to any shared mutable record with more than one writer. It works for an inventory row, a rate-limit bucket, or a balance. The table of field owners costs an afternoon to write down. It pays for itself the very first time a value drifts, because it converts an open-ended hunt into a strict lookup. It applies unchanged whether the backend is Postgres, a document store, or a key-value store.

What I would check first

  1. Check the event log attribution for the drifting field. If the field has only one writer, this rules out an architectural race and points to a logic error inside that single writer. If it has two or more writers, it rules out a logic error and confirms an architectural race.
  2. Inspect the fields modified by the reconciler during drift events. If the reconciler mutates fields authoritative to the webhook or dispatcher rather than its own partition, this isolates the drift to reconciler overreach. This rules out an in-flight race condition and confirms a partition boundary violation.
  3. Check whether the field mutation originates from an unauthorized layer such as a view or direct live-session query. If updates occur outside the designated admission path, this isolates an unpartitioned cross-layer write rather than an overlap between dispatcher and webhook.

Why locks fail to protect shared state

Database locks serialize writes across concurrent transactions. When a webhook handler clears a hold and a reconciler independently repairs that same hold, executing under a transaction lock guarantees that one decrement completes immediately before the other begins. Both operations succeed because numeric decrements are mathematically valid and pass type checking. Serialising the writes preserves the double-decrement instead of preventing it, leaving the final counter corrupted.

Partitioning the fields practically

Partitioning shared state requires grouping related fields in the data store and assigning each group to exactly one authoritative writer.

In the file that defines the state group, record the single code path permitted to write to it. A dispatcher decrements capacity holds during call admission, while the webhook handler clears holds upon room termination. The reconciler operates exclusively on its own assigned fields and never repairs a field governed by another path.

Where static types cannot prevent multiple writers, developer-invoked lint rules enforce the boundary:

  • Block direct wall-clock reads inside the scheduler.
  • Block direct queries of the live-session store outside the admission path.
  • Block reaching into admission state from a view layer.

This partitioning pattern applies across storage backends, including Postgres, document stores, and key-value stores, protecting shared records such as inventory rows, rate-limit buckets, and balances.

Common questions

Why does my concurrency counter drift even with database locks?

Locks serialize concurrent writes, but they do not prevent two different systems from executing valid logic. If a webhook and a reconciler both decide to decrement a hold, a lock just forces them to do it one after the other.

How do you fix a double-decrement in shared state?

Partition the database fields by owner and strictly assign a single code path to write each field group. Adding a second writer to a group is a correctness violation. This converts an open-ended hunt into a strict lookup.

Can I use CI rules to enforce the single writer principle?

You can, but you do not have to block deployments to get the value. Developer-invoked lint rules treated as structural tests provide immediate local feedback. This enforces architectural boundaries locally without wiring checks into deployment gates.

How do I debug which system corrupted the counter?

Add per-field write attribution to your event log. Every state change must record the exact actor, such as the webhook handler or the task queue, that authorised the write. A drift investigation then starts with who wrote it instead of a repository grep.

Scheduling and capacity

Enforcing maximum concurrent SIP calls without race conditions

When outbound calls exceed your SIP trunk channel limits, the cause is usually a read-then-write race condition in your scheduling logic.

Scheduling and capacity

The scheduler holds stale capacity after a call ends or kills a live session prematurely

How to fix a voice agent scheduler that holds stale trunk capacity after calls end, or kills live conversations because a timer decided they ran too long.