Video in progress

Operations on one account must run in strict order and without locks. How do you design a single-writer or partitioning approach?

Each key (for example, an account ID) is permanently assigned by hash to one executor: a single thread or a single queue. Then order within one key is preserved naturally, no shared lock is needed, and different keys run in parallel.

📖 Answer

The lock-based approach is familiar: an account lock on every operation, a lock order for transfers between two accounts, and the risk of contention and deadlock. The single-writer approach changes the question: not "how do we protect it", but "how do we get rid of shared state".

A simple in-JVM variant:

final class PartitionedExecutor {
    private final ExecutorService[] lanes;

    PartitionedExecutor(int n) {
        lanes = new ExecutorService[n];
        for (int i = 0; i < n; i++) {
            lanes[i] = Executors.newSingleThreadExecutor(
                    Thread.ofPlatform().name("lane-" + i).factory());
        }
    }

    CompletableFuture<Void> submit(long accountId, Runnable op) {
        int lane = (int) Math.floorMod(accountId, (long) lanes.length);
        return CompletableFuture.runAsync(op, lanes[lane]);   // one account always goes to the same lane
    }
}

Inside a lane the state belongs to a single thread, so a plain HashMap is enough.

At the system level this is natural in Kafka: the account ID is the message key, messages in one partition are ordered, and each partition is read by one consumer. The LMAX Disruptor architecture is built on this same idea.

The costs:

  • Hot key. One very active account occupies a whole lane, and its neighbors wait. In monitoring, watch for imbalance across lane queues.
  • Operations that touch several keys. A transfer from A to B touches two lanes. It's usually split into two steps like a saga: debit A (in A's lane), then credit B (in B's lane), with compensation.
  • Blocking IO inside a lane stops the whole lane. Lanes are only for fast, in-memory work; IO has to be batched or moved out asynchronously.
  • Rebalancing. If the number of lanes changes, keys move to other lanes, and ordering can break during the transition. Kafka rebalance has the same problem.

I pick this approach if ordering is a business requirement and lock contention has been confirmed by measurement. For ordinary CRUD, optimistic locking in the DB is simpler and enough.