Mustafa Nevfel

Snippets

Short, reusable patterns taken from the notes: the answer, the code, why it works and when not to use it.

From An invoice is a snapshot, not a calculation

  1. Snippet · SQL

    Gapless invoice numbering in PostgreSQL without a sequence

    Increment a counter row with UPDATE ... RETURNING inside the issuing transaction: the row lock orders issuers and a rollback gives the number back.

  2. Snippet · SQL

    Make issued invoices immutable in PostgreSQL

    A BEFORE UPDATE OR DELETE trigger catches mistakes, privileges enforce it, and corrections are linked credit notes with a derived adjusted total.

  3. Snippet · TypeScript

    Store money as integer minor units and round tax per line or document

    Do the arithmetic in bigint minor units with an explicit tie rule. Five 1.10 lines at 8% tax to 0.45 per line or 0.44 per document, so store the scope.

From Design the reconnect first: sequence numbers, replay and snapshots

  1. Snippet · SQL

    Gap-free per-stream sequence numbers in PostgreSQL

    Bump a counter row per stream in the same transaction as the change; the row lock makes sequence order equal commit order, with no gaps.

  2. Snippet · TypeScript

    Handle duplicate and missing WebSocket messages on the client

    Drop sequence numbers at or below the last applied, resync on a gap or epoch change, and let snapshots replace state instead of applying to it.

  3. Snippet · TypeScript

    Resume a WebSocket stream after reconnect without losing messages

    On reconnect, subscribe with buffering first, then replay the gap or send a snapshot, then drain the buffer. The reverse order loses messages.

From Run AI agents like queue workers: briefs, budgets and stop reasons

  1. Snippet · TypeScript

    Bounded AI agent loop with step, token, time and error budgets

    Check every budget before each step, share one AbortSignal with the model call and the tools, and end with a typed out_of_budget that names the limit.

  2. Snippet · TypeScript

    Map Claude stop_reason to a typed agent loop outcome

    Map stop_reason in the adapter to done, blocked or out_of_budget, resume on pause_turn, and throw on anything unexpected rather than reporting success.

  3. Snippet · TypeScript

    Derive idempotency keys for AI agent tool calls

    Hash the task id, tool name and canonical arguments in the harness, and pass the key to the system that owns the side effect, not only to a local ledger.