Skip to the content.

How it works

SyncLane is four pieces around one table: a planner that inserts rows, worker slots that take them, a runner that drives your handler, and a handful of statements that move a row from one status to the next. This page goes through them in the order a job meets them.

At a glance

How a SyncLane job runs: planned, taken with one UPDATE, run page by page with the cursor saved under the lease, completed; what happens when a page fails, when a worker goes away, and when the API says slow down.

flowchart LR
    owners["Your accounts<br/>(IOwnerSource)"] --> planner["Planner<br/>what should exist<br/>minus what exists"]
    planner -->|"insert, on conflict do nothing"| table[("synclane.jobs")]
    table -->|"take the next job<br/>whose lane is free"| worker["Worker slot"]
    worker --> handler["Your handler<br/>one page"]
    handler -->|"cursor + count"| worker
    worker -->|"save cursor, renew lease"| table
  1. Plan. Once a minute the planner asks your IOwnerSource who is connected, reads in one query what already exists for them, and inserts what is missing. A snapshot type gets one initial job. A windowed type gets its history in slices back to the horizon, anchored to midnight UTC so that two calls on the same day produce the same slices. Each period adds one recurring job; for a windowed type its window starts where coverage ends.
  2. Take. A worker slot takes the next job that is due and whose lane has nothing running. Urgent jobs run first, then owners moved forward, then high, normal and low; within a level, types run in the order you declared them, and within a type the newest window runs first, so what is new is never stuck behind history. The row is marked running with the worker’s name and a lease.
  3. Run. The handler is called page by page. After every page the cursor and the record count are saved and the lease is renewed. A heartbeat renews the lease while a slow page is in flight.
  4. Finish. No next cursor means completed. An exception means failed and a delay that doubles with every attempt; a JobThrottledException means a longer delay. Attempts count since the last saved page, so a long job that fails now and then still finishes. When the regular attempts are used up the job is deferred: it steps aside, the rest of its lane runs, and it gets one more attempt once the lane is idle. If that fails too it is abandoned and waits for you.
  5. Recover. A worker that stops hands its job back with the cursor. A worker that dies stops renewing its lease, and another worker takes the job over; the dead worker’s writes are refused from then on.
stateDiagram-v2
    [*] --> pending: planned
    pending --> running: taken
    running --> completed: no next cursor
    running --> failed: attempt failed
    failed --> running: delay is over
    running --> pending: worker is stopping
    running --> deferred: regular attempts used up
    deferred --> running: lane is idle
    running --> abandoned: deferred attempt failed
    abandoned --> pending: requeue
    completed --> [*]

What a job looks like

This is a row from the demo, taken while it was running. The job covers one 30-day slice of an account’s orders. Its second page keeps failing, so it has done 50 records, is on its fourth attempt and will run again at next_run_at, from cursor 50:

id               | 33
queue            | shops
owner            | globex
lane             | globex
type             | orders
mode             | initial
status           | failed
priority         | 1
window_start     | 2026-08-08 00:00:00+00
window_end       | 2026-09-07 00:00:00+00
dedup_key        | initial:2026-08-08T00:00:00Z
cursor           | 50
processed_count  | 50
attempt_count    | 4
error            | InvalidOperationException: The shop returned a page that could not be read.
next_run_at      | 2026-10-07 12:15:50.548901+00
leased_by        |
lease_expires_at |
created_at       | 2026-10-07 12:15:12.39661+00
started_at       | 2026-10-07 12:15:17.621544+00
heartbeat_at     | 2026-10-07 12:15:35.045812+00
completed_at     |

Two indexes carry the guarantees

Neither guarantee depends on a lock or on code remembering to check something:

The second one is not decoration. With that index dropped, 24 workers taking jobs from 3 lanes put two jobs of one lane to work 170 times in a run of 600 jobs. With the index: zero.

The table

Jobs are in synclane.jobs. The full definition is in schema.sql. Beside it, synclane.coverage keeps what the planner needs per owner and type, synclane.rate_buckets the rate budgets, synclane.pauses and synclane.budget_limits what operators set, synclane.actions what they did, synclane.instances the running processes, and synclane.migrations which schema version the database has.

Column Meaning
queue The queue. Each queue has its own worker slots and settings.
owner Who the job works for: one connected account.
lane Jobs with the same lane never run at the same time. Defaults to the owner.
type The job type, which selects the handler.
mode initial (first load), recurring (periodic refresh) or manual (enqueued by hand).
status pending, running, completed, failed, deferred or abandoned.
priority Lower runs first: the band of the job’s level (urgent, high, normal 0, low) plus the position of the type’s declaration, less 1,000,000 when an operator moved the owner forward.
window_start, window_end The range the job covers, if it has one.
dedup_key What makes the job unique for its owner and type.
arguments What the job was enqueued with, for its handler to read. Text the caller chose; SyncLane never reads it.
cursor Where the next page starts.
processed_count Records handled so far, over all pages and attempts.
attempt_count How many times a worker has picked the job up since it last saved a page. A saved page sets it back to 1.
error The last failure.
next_run_at The job is not picked up before this moment.
leased_by, lease_expires_at Who holds the job and until when.
lease_generation Which lease of the job this is: one more each time a worker takes it. Every write of a running job is made only while it still matches.
created_at, started_at, heartbeat_at, completed_at, updated_at The life of the row.

Status and mode are stored as text, so the table reads without a legend.

Planning

Covered in planning.md. In short: one query reads the summary and the open jobs of all owners, a pure function works out what is missing, one insert adds it and updates the summary.

Taking a job

A worker slot takes its next job with one statement:

UPDATE synclane.jobs AS j
SET status = 'running',
    leased_by = @worker,
    lease_generation = j.lease_generation + 1,
    lease_expires_at = @lease_expires_at,
    attempt_count = j.attempt_count + 1,
    started_at = COALESCE(j.started_at, @now),
    heartbeat_at = @now,
    updated_at = @now
WHERE j.id = (
    SELECT c.id
    FROM synclane.jobs AS c
    WHERE c.queue = @queue
      AND c.next_run_at <= @now
      AND (c.status IN ('pending', 'failed')
           OR (c.status = 'running' AND c.lease_expires_at <= @now)
           OR (c.status = 'deferred' AND NOT EXISTS (
                   SELECT 1
                   FROM synclane.jobs AS w
                   WHERE w.queue = c.queue AND w.lane = c.lane AND w.id <> c.id
                     AND w.status IN ('pending', 'running', 'failed'))))
      AND NOT EXISTS (
          SELECT 1
          FROM synclane.jobs AS r
          WHERE r.queue = c.queue AND r.lane = c.lane AND r.id <> c.id
            AND r.status = 'running')
    ORDER BY (c.status = 'deferred'), c.priority, c.window_start DESC NULLS LAST, c.next_run_at, c.id
    LIMIT 1
    FOR UPDATE OF c SKIP LOCKED)
RETURNING j.*;

The statement in JobSql.cs is this one with the schema name filled in and the returned columns written out. Reading it from the inside out:

Why the index is needed on top

SKIP LOCKED keeps two slots off the same row. It does not keep them off the same lane. Slot A picks job 1 of lane X; slot B, in the same instant, skips job 1 because it is locked, and picks job 2 of lane X. Neither sees a running job in lane X yet, because neither has committed.

The table has this index:

CREATE UNIQUE INDEX jobs_one_running_per_lane
    ON synclane.jobs (queue, lane) WHERE status = 'running';

With it, the database refuses the second update with a unique violation. SyncLane catches that and asks again; this time the lane is visibly busy and another lane is chosen. There is no lock to acquire and none to forget to release.

Measured on a laptop: 24 workers, 3 lanes, 600 jobs. Without the index, two jobs of one lane were at work together 170 times. With it, never. The test Many_workers_never_put_two_jobs_of_one_lane_to_work keeps that true.

Running a job

The runner calls your handler with the job, saves what it returns, and calls it again:

repeat
    page = handler.RunPageAsync(job)             # a new service scope for every page
    save cursor = page.NextCursor,
         processed_count += page.Processed,
         renew the lease
until page.NextCursor is null
mark completed

The same, with everything a page touches:

sequenceDiagram
    participant W as Worker slot
    participant J as synclane.jobs
    participant H as Handler or recipe
    participant B as Rate budget
    participant A as Their API
    participant T as Your tables
    W->>J: take the next due job whose lane is free<br/>(running, leased_by, lease_generation + 1)
    loop every page
        W->>H: run one page from the cursor
        H->>B: wait for a token of the account
        H->>A: request the page
        A-->>H: records, and where the next page starts
        H->>T: upsert the records
        H-->>W: next cursor, record count
        W->>J: save the cursor and the count, renew the lease<br/>(only while the lease is still this worker's)
    end
    W->>J: completed (only while the lease is still this worker's)

Three things happen around that loop.

A heartbeat. While the handler is inside a page, a timer renews the lease every third of LeaseDuration. The lease therefore only has to be long enough to notice a dead process. It does not have to be longer than your slowest page.

Fencing. Every write the runner makes to a job (a page saved, a heartbeat, the job completed, failed, postponed or handed back) ends with WHERE id = @id AND status = 'running' AND leased_by = @worker AND lease_generation = @generation. If the lease ran out and another worker took the job, those writes change nothing; the old worker notices and stops. It cannot overwrite the new holder’s cursor or status, however long it was paused, and the takeover never waits for a heartbeat. The generation is what makes this hold when the two workers have the same name, as two containers that share a hostname and both run as process 1 do.

Fencing covers what SyncLane writes. What the handler wrote to your own tables before its next save was refused stays written: a worker that wakes after its job was taken over may finish the page it was in. That is why a page is handled at least once and writes should be upserts; WriteToPostgres keeps the newer version of a record when it is told which field holds the version.

A new scope per page. The handler is resolved from a fresh dependency-injection scope for each page, so a DbContext or anything else scoped does not accumulate state over a job with hundreds of pages.

When an attempt fails

What happened New status When it runs again
Exception, attempts left failed After RetryBaseDelay, doubled per attempt, capped at RetryMaxDelay
JobThrottledException failed After the wait it named, or ThrottleBaseDelay doubled per attempt, capped at ThrottleMaxDelay
JobPostponedException pending, the attempt not counted After the wait it named. A rate budget throws it when a token is far away, and a recipe with a budget when the API says “slow down”
Its queue or owner is paused pending, the attempt not counted, cut where it was After the resume, from the last saved page
Exception on attempt MaxAttempts deferred When nothing else is pending, running or waiting for a retry in its lane
Exception on the deferred attempt abandoned After a requeue. A recurring job is replaced by the next period’s, which covers its window too
JobAbandonedException abandoned The same
No handler for the type abandoned After a requeue

The cursor and the processed count are never reset by a failure. Whatever status a job leaves running with, it comes back at the page it stopped on.

Attempts count failures since the last saved page. A job that saves a page has shown that it works, so its count starts again. A job of a thousand pages that meets a timeout now and then, hours apart, finishes; a job that fails five times on the same page is deferred. Progress is never lost, because the cursor is saved, so a job that keeps making progress always reaches the end.

Why deferred exists

Without it there are two choices when a job runs out of attempts, and both are bad. Keep retrying, and one broken slice of history holds up everything behind it in the lane, including the fresh data. Give up at once, and a slice that only failed because the lane was busy and rate limited is lost until a human notices.

deferred takes the job out of the way, lets the rest of the lane finish, and then gives the job one attempt with the lane to itself. If it fails even then, it is abandoned and visible.

When a worker stops or dies

Stops (deployment, scale-down): the host’s stopping token cancels the handler, the runner writes the job back as pending with its cursor, and gives the attempt back, because being interrupted by your own deployment is not a failure.

Dies (out of memory, node gone): nobody renews the lease. Once lease_expires_at has passed, the job is a candidate again and another slot takes it over, from the cursor. The attempt counts. A job that has been picked up more often than MaxAttempts + 1 without ever reporting a result is abandoned instead of being run again, so a job that takes its worker down every time does not do so forever.

Has its job replaced or closed (EnqueueOrReplaceAsync, CompleteAsync): the call raises the job’s lease_generation, so every write of the attempt under way misses, exactly as after a takeover. A replaced job stays running and keeps its lane closed; it is taken again with its new arguments when the lease runs out. A closed job is completed at once and its lane is free, while the attempt may still be inside the handler until its next page or heartbeat tells it the lease is lost.

The lane is closed by the row, not by the lease

An earlier version of this design let a lane move on when the lease of its running job had expired. Then this happened: an account was being throttled, pages were taking around nine minutes each with all the waiting and retrying, the lease was ten minutes, and sooner or later one page ran past it. Another worker saw “nothing alive in this lane”, took the account’s next job and started calling the same rate-limited API in parallel. That produced more throttling, which made pages slower, which made more leases go stale.

Since then a lane is closed as long as it has a row in running, whatever its lease says. An expired lease allows exactly one thing: taking over that same job. Together with the heartbeat, a slow page no longer looks like a dead worker in the first place.

What your handler has to do