# SyncLane > SyncLane is a .NET library that runs sync jobs against other people's APIs from one PostgreSQL table: it plans what each connected account needs (history in slices, then periodic refreshes), runs it page by page with leases and retries, keeps to each API's rate limit across every instance, and saves a cursor after every page so nothing is lost on a crash. Instead of a hand-written handler, a job can run a recipe: a JSON file (`.jsonc`) that says how to read one API resource, page by page, into a destination. Every page listed under Docs and Running it, in one file: [llms-full.txt](https://raw.githubusercontent.com/synclane-dev/synclane/main/llms-full.txt). The same pages as a website: https://synclane-dev.github.io/synclane/, with this file at https://synclane-dev.github.io/synclane/llms.txt. Notes for writing recipes: - Start from a curl that works. `synclane init` (the `SyncLane.Cli` tool) sends it once and writes a draft with a comment beside every guess; `synclane test` runs a recipe for two pages without a database and reports structure, never data. `synclane mcp` gives an AI assistant the same as tools; with the .NET 10 SDK it runs without installing as `dnx SyncLane.Cli --yes mcp`, and it is listed in the MCP Registry as `io.github.synclane-dev/synclane`. - A recipe never holds a credential. It names one (`"auth": { "type": "bearer", "credential": "example-shop" }`); the application's credential store, or an environment variable when testing, supplies the value. Never write a token, key or password into a recipe, a curl you suggest, or a reply. - Every field is described in the JSON Schema; put `"$schema"` at the top of a recipe for completion in an editor. - Requests go only to the host a recipe names, or to one of the hosts it lists in `request.hosts` when the host is made from the owner's values; redirects are not followed. Values an account needs besides its key (a marketplace, a region) come from the owner as `{{owner.}}`; `{{request.id}}` is a new UUID per request. - Errors carry a stable code such as `SL5106`; the catalog says what each means and how to fix it. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/integrating.md # Integrating SyncLane into an application This page takes an existing .NET application from nothing to data flowing in production, step by step. It is written so that you can hand it to an AI assistant in your project ("read this page and integrate SyncLane"), and so that a developer can follow it alone. Every call on it exists in the current version. The order is fixed: write down what the project does today, answer the questions, make the decisions, follow the steps with a check after each, prove the data is the same as before, then run the production trial. Nothing below asks you to change SyncLane; everything happens in your application. ## For an AI assistant reading this page - **The project's own rules come first.** Before anything else, read the project's `CLAUDE.md` and `ARCHITECTURE.md`, and any file of the same kind it has (`AGENTS.md`, `CONTRIBUTING.md`, `.editorconfig`, a coding standard). Everything on this page is applied inside those rules, never over them: where they disagree, follow the project's rule and tell the user which part of this page gave way. If the project keeps a decision log, record the decisions of [section 3](#3-decisions) there, in its format. - **Write no comments in the code.** Names and small methods say what the code does; the reasons go in the pull request. The one exception is a comment the project's own rules require, such as XML documentation on public members. `synclane init` writes a comment beside every guess in a recipe draft: confirm each guess with the user, then remove its comment. - **Keep what the project does.** The integration changes when and how the work runs, not what is fetched, how it is mapped, or what the business rules decide. Write down today's behaviour first ([section 1](#1-what-the-project-does-today)) and prove at the end that the data is the same ([section 5](#5-prove-it)). Speed may improve; results may not change. - **Leave the existing tests alone.** Every test that passed before passes after, unchanged. Never edit, skip or delete a test to make it pass: a test that fails means the behaviour changed. - **If the project already uses SyncLane, start at [section 7](#7-upgrading-an-existing-integration).** The steps of section 4 are for a project without it; applied to a running integration, some of them would reload its history or set its web instances to work. - **Ask before you write code.** Work through [the questions](#2-questions-to-answer-first) with the user. Where the user does not know, take the default in the table and say that you did. - **Use only what is documented.** The calls, settings and types on this page and the pages it links to. If something seems to be missing, say so; do not invent an overload or a setting. - **Follow the project's conventions.** Its layers, folder structure, DI style, naming and test framework. SyncLane's own repository rules (SyncLane's `CLAUDE.md`) are for changing SyncLane, not for applications that use it. - **Never put a credential anywhere you write.** Not in code, a recipe, `appsettings.json`, a test, a curl you suggest or a reply. Credentials come from the project's own storage through an `ICredentialStore`, or from an environment variable while testing. - **Finish each step before the next.** Each step ends with "Done when"; check it, and report what you saw. - **Stop and ask** when a step's check fails twice, when the project's database is not PostgreSQL 14 or later, or when the target framework is below .NET 10. ## 1. What the project does today Before any decision, write down every piece of sync work the project does now: scheduled jobs, hosted services, timers, "refresh" endpoints. One row each. The table is the specification of the integration, and it goes into the pull request. | Column | Example | | --- | --- | | Name and where it lives | `OrderSyncJob`, a recurring job every 15 minutes | | What it calls | `GET /orders?updated_after=` for each connected shop, 100 per page | | For which accounts | shops that are connected and have an active subscription | | Rules on the way | skips draft orders; converts the currency; computes the net total with `PriceCalculator` | | Where it writes, by which key | `Orders`, upsert by `(ShopId, ExternalId)`; `OrderItems` replaced per order | | Side effects | publishes `OrderImported`; sends a low-stock email | | Time range | since the last successful run, minus 5 minutes | | How it fails today | retries 3 times, then logs | | Who starts it by hand | the "refresh" button on the orders page | **Must not change:** which records are fetched (accounts, filters, time ranges), how they are mapped and validated, the keys they are stored under, and the side effects. **May change:** when and how often the work runs (within what users expect), how many accounts load side by side, retries and backoff, and speed. How the rows translate: - Each row becomes a job type ([step 5](#step-5-declare-the-queue)), or stays where it is when users wait for its answer ([D2](#d2-which-process-does-what)). - Each rule moves into the handler by **calling the code that implements it today**, not by copying it. A business rule keeps living in one place. - "Since the last run" becomes the job's window: SyncLane starts each recurring window where the last one ended, and `overlap` replaces the "minus 5 minutes". - "Retries 3 times, then logs" becomes the failure policy: retries with backoff, then `deferred`, then `abandoned`, all visible in the monitor. ## 2. Questions to answer first | # | Question | Why it matters | Default when nobody knows | | --- | --- | --- | --- | | Q1 | Which external API, and which resources of it (orders, products, invoices)? | Each resource becomes a job type. | None; this one must be answered. | | Q2 | For each resource: is it read by **time range** (new and changed records since a date), as a **full list** every time, or only **on demand**? | Decides `Windowed`, `Snapshot` or `Handle` ([step 5](#step-5-declare-the-queue)). | Time range, if the API takes a date filter. | | Q3 | Who is an **owner**: a connected account, store, tenant? Where are they stored, and what is a key that never changes? | The planner plans per owner. A key that changes reloads the owner's history. | The primary key of the table that holds connected accounts. | | Q4 | Do several owners share one set of credentials or one rate limit? | Owners that share a limit must share a lane and a budget key. | No: every owner has its own lane and key. | | Q5 | What rate limit does the API publish, per account? | It becomes the rate budget. | A generous ceiling with `start: 0.25`; the budget learns below it. | | Q6 | How much history is needed, and how many records does the largest owner have per month? | Sets `horizon` and `slice`. One slice is one job, the largest unit of work that cannot be split. | Horizon 30 days and slice 7 days for the trial; raise later, only the gap is fetched. | | Q7 | How fresh must the data be? Can records appear late, with an older date? | Sets `every` and `overlap`. | `every` 15 minutes, `overlap` 10 minutes. | | Q8 | Is the API a plain JSON list, page by page, or does it need business logic (several calls per page, reports, GraphQL, an SDK the project already uses)? | Recipe or handler ([decision D1](#d1-handler-or-recipe)). | Handler, if in doubt. | | Q9 | Where do the records go: tables the project already has, or new ones? | The handler or the sink writes them. Writes must be upserts. | The project's own tables, through its own data layer. | | Q10 | Where are the API credentials stored today, and who refreshes them? | The handler's client or an `ICredentialStore` reads them from there. | Where they are today; SyncLane stores none. | | Q11 | Which PostgreSQL database, and is there a connection pooler (PgBouncer) in front of it? | A pooler in transaction mode needs `ListenConnectionString`. | The application's own database, no pooler. | | Q12 | Who changes the database schema: the application at start-up, or the project's migrations? | `CreateSchema`. | SyncLane at start-up (`CreateSchema = true`). | | Q13 | How is the application deployed: one process, or web instances and a separate worker? | Who runs the planner and the workers ([decision D2](#d2-which-process-does-what)). | One process does everything. | | Q14 | Does another system already sync this data? | Its history is marked loaded instead of fetched again ([step 11](#step-11-move-from-an-existing-sync)). | No. | | Q15 | Should users trigger a refresh (a button, a webhook)? | `SyncNowAsync` ([step 9](#step-9-refresh-on-demand-and-new-accounts)). | No. | | Q16 | Who may see and repair jobs, and through what? | The monitor over HTTP, behind an authorization policy ([step 8](#step-8-the-monitor-over-http)). | Nobody yet; add it before production. | | Q17 | What do the other applications on the same schema call themselves, and their queues? | The application's name and queue names must be its own ([D2](#d2-which-process-does-what)); `GetInstancesAsync` lists those already registered. | A short lower-case name of the project, such as `shop`, and queues starting with it. | ## 3. Decisions ### D1. Handler or recipe | Use a **recipe** when | Use a **handler** when | | --- | --- | | The API returns JSON records page by page, and you only fetch them and store them. | A page needs business logic: several calls, a report to request and wait for, a GraphQL query, an SDK or client the project already has. | | Paging is by page number, offset, cursor, next URL or `Link` header. | Records must be transformed or validated with the project's rules before they are stored. | | Authentication is bearer, basic, an API key, OAuth 2.0 or a request signer. | The data goes to several tables in one transaction. | Decide per row of [the inventory](#1-what-the-project-does-today) and write the decision into it. A row with any rule, mapping or side effect is a handler: the rule stays in the project's code and the handler calls it. A recipe is a JSON file; [Recipes](recipes.md) describes every part, and `synclane init` writes one from a curl that works ([with an AI assistant](ai.md)). A handler is a class with one method. One queue can mix both: each job type chooses. ### D2. Which process does what **What a process is comes from its settings; whether it works comes from the database.** The settings name the process: its application (`SyncLane:Application` in `appsettings.json`, committed) and, when one build runs as web and worker, its role (`SyncLane__Role` in the worker's environment). They never say whether it runs workers or the planner: leave `RunWorkers` and `RunPlanner` out, at their default `true`, and decide from the monitor with a switch per application and role, kept in the database ([Switching an application on and off](operations.md#switching-an-application-on-and-off)). A switch survives restarts, deploys and new replicas, because each instance reads it when it starts, before it takes a job; it changes without a deploy, and every change is logged with who and why. | What | Where | Example | | --- | --- | --- | | The application's name, its own on the schema | `appsettings.json`, committed | `"SyncLane": { "Application": "shop" }` | | The role, only when one build runs as web and worker | the worker's environment | `SyncLane__Role: "worker"` | | Names of new queues, starting with the application's name | code ([step 5](#step-5-declare-the-queue)) | `shop.stores` | | Whether it runs workers and the planner | a switch in the database, set from the monitor | `POST /synclane/switch?application=shop&workers=false&reason=…` | | Whether it listens for job changes | a switch of its own, set from the monitor | `POST /synclane/switch/listen?application=shop&listen=false&reason=…` | | Layout | When | Settings | | --- | --- | --- | | **One process** | Small and medium loads; the default. | Nothing to set. | | **Web and worker, one image** | Syncing must not take CPU or memory from user requests. | The same build runs as two containers; the worker's environment gives it a role, `SyncLane__Role=worker`. Before the first deploy, the web instances (no role) are switched off and the worker role on, from the monitor ([step 6](#step-6-split-the-roles-if-you-chose-to)). Nothing in `appsettings.json` turns anything off. | | **Several workers** | More owners loading side by side. | Run more copies of the worker. Jobs, planning and budgets are shared through the table; nothing else to configure. | - Give the application a name of its own. The default is the entry assembly's name, and projects built from one template often share it (`Api`, `WebApi`): two applications under one name are one to SyncLane, so one switch stops both and the monitor shows them as one. SyncLane warns when it sees it (`InstanceInfo.SharesNameWith`, a Degraded health check), but only a name of its own prevents it. A running integration keeps the name it has ([step U3](#step-u3-name-the-application-and-its-roles)). - Keep one application per queue, and start the name of every new queue with the application's name; never rename a queue that already runs ([section 7](#what-never-changes-in-an-upgrade)). Copies of one application share their queues; a second application that runs the same queue is refused at start-up (`SL1011`). An instance switched off, workers and planner, claims no queue and may call `ISyncLane` and the monitor freely. - Run one process per container. If a worker and a web host share a container and one of them dies, the orchestrator does not restart it. - The worker needs no open port. Its state is in the database: the monitor reads it from any instance. - Work the user waits for (an answer on screen) stays in the web process. Work nobody waits for (fetching, reports, sending data out) becomes a job, and a "refresh" button enqueues it and returns at once. ### D3. Owner, lane and budget key - **Owner key:** stable and unique per queue, usually the connected account's id. Never a name or an email. Give one account the same key on every queue, so the monitor counts its jobs on all of them together (`GetJobOwnersAsync`). - **Lane:** leave it out, and each owner gets its own lane. Give owners that share credentials or a rate limit the same lane, so their jobs never run at the same time. - **Budget key:** usually the owner key. Owners that share one rate limit pass one key. - **Name:** what people call the owner, shown and searched by the monitor. It may change at any time. - **Values:** what a recipe needs besides the key, such as a region or a marketplace, as `JobOwner.Values`. ### D4. Where the code lives Keep everything that belongs to SyncLane in one place, so it can be found, tested and, if need be, removed. Follow the project's own layers and names; this shape works as a folder of a single project or of its infrastructure layer: ``` Sync/ SyncRegistration.cs AddShopSync(services, configuration): every AddSyncLane, AddBudget and AddSyncLaneHttp call Owners/ ConnectedShops.cs IOwnerSource Handlers/ Orders/OrderHandler.cs one folder per job type Products/ProductHandler.cs Recipes/ orders.jsonc copied to the output Credentials/ ShopCredentials.cs ICredentialStore over the project's own storage Sinks/ OrderSink.cs IRecordSink, when a recipe writes to the project's tables ``` - **Handlers are thin.** Fetch one page, call the project's existing services for the rules, write through its existing repositories. No business rule is written twice. - **In a layered project,** what the domain needs stays in the application layer; handlers, the owner source and the credential store go where the infrastructure lives, because they touch the database and the network. - **One registration method.** `Program.cs` gets one line, `builder.Services.AddShopSync(builder.Configuration);`, and the end-to-end test of [section 5](#5-prove-it) calls the same method. - **Recipes travel with the build:** `` in the project file. - **The old jobs stay** until the cut-over in [section 5](#5-prove-it), and are deleted in a later change. ## 4. Steps ### Step 1. Add the packages ```bash dotnet add package SyncLane dotnet add package SyncLane.Http dotnet add package SyncLane.AspNetCore ``` `SyncLane.Http` is needed only for recipes, `SyncLane.AspNetCore` only for the monitor over HTTP. Their namespaces: `SyncLane` (the engine: `AddSyncLane`, `IJobHandler`, `IOwnerSource`, `ISyncLane`, `ISyncLaneMonitor`), `SyncLane.Http` (`AddSyncLaneHttp`, `HttpRecipeHandler`, `ICredentialStore`, `IRecordSink`) and `SyncLane.AspNetCore` (`MapSyncLane`). **Done when** the project builds. ### Step 2. Connection and configuration Add a connection string, and a `SyncLane` section with the application's name and the numbers that change per environment: ```json { "ConnectionStrings": { "Postgres": "Host=db;Database=app;Username=app" }, "SyncLane": { "Application": "shop", "Queues": { "shop.stores": { "Concurrency": 2, "Types": { "orders": { "Every": "00:15:00" } } } } } } ``` `Application` is the name the monitor, the switches and the other applications on the schema know this one by: lower case, short, its own, and the same in every environment. Do not add `RunWorkers` or `RunPlanner`; whether the application works is a switch ([D2](#d2-which-process-does-what)). The password comes from where the project keeps secrets, never from a committed file. Behind PgBouncer in transaction mode, also set `SyncLane:ListenConnectionString` to a connection that goes around the pooler ([Behind a connection pooler](operations.md#behind-a-connection-pooler)). If none can, switch listening off from the monitor before the first deploy, `SetListeningAsync("shop", null, listen: false, reason: "behind the pooler", by: user)`, so the application never tries; its workers then find jobs every `PollInterval`. `SyncLane:ListenForChanges` stays out of the settings, like `RunWorkers` and `RunPlanner`. **The schema needs no work by hand.** With the defaults, the first start creates the schema `synclane` in the database of `ConnectionString`, with every table and index, behind a lock so instances that start together do not collide; each later SyncLane version adds its migrations the same way. SyncLane never touches the project's own tables. Several applications can share one database and one schema: each declares its own queues, and the monitor of any of them shows every application's jobs ([Several applications on one schema](operations.md#several-applications-on-one-schema)). Keep the default name unless the project's database rules say otherwise (`SyncLane:Schema`, lower case). If the application's database user may not create a schema, run the script from the project's migrations instead ([step 12](#step-12-deploy)). **Done when** the application starts with the section present and the connection string resolves. ### Step 3. The owner source One class that returns who is connected now. The planner calls it once a minute. ```csharp public sealed class ConnectedShops(AppDb db) : IOwnerSource { public async Task> GetOwnersAsync(string queue, CancellationToken cancellationToken) => await db.Shops .Where(shop => shop.IsConnected) .Select(shop => new JobOwner(shop.Id.ToString(), null, shop.Name) { Priority = shop.IsNew ? JobPriority.High : JobPriority.Normal }) .ToListAsync(cancellationToken); } ``` - Inside a query, give `JobOwner` its arguments in order: the key, the lane (`null` for a lane of its own) and the name. A named argument out of order, such as `Name: shop.Name`, does not compile in an expression tree. - A `High` priority for new accounts makes their history load before the others'. - Return only owners that should have jobs. An owner left out gets no new jobs; the jobs it already has still run until they are cancelled ([step 10](#step-10-accounts-that-disconnect-or-leave)). - It is resolved in a scope of its own, so a scoped `DbContext` is fine. **Done when** it returns the expected owners in a test or a debug run. ### Step 4a. A handler One page per call. SyncLane saves the returned cursor after every page and calls again until the cursor is `null`. ```csharp public sealed class OrderHandler(IShopClient client, OrderRepository orders, RateBudgets budgets) : IJobHandler { public async Task RunPageAsync(Job job, CancellationToken cancellationToken) { var permit = await budgets.WaitAsync("shop-api", job.Owner, cancellationToken); var response = await client.GetOrdersAsync(job.Owner, job.WindowStart, job.WindowEnd, job.Cursor, cancellationToken); if (response.IsThrottled) { var pause = await budgets.ThrottledAsync(permit, response.RetryAfter, cancellationToken); throw new JobPostponedException("The shop API asked to slow down.", pause); } if (response.IsUnauthorized) throw new JobAbandonedException("The shop's access was revoked; reconnect it."); await orders.UpsertAsync(job.Owner, response.Orders, cancellationToken); return new JobPage(response.NextCursor, response.Orders.Count); } } ``` The rules of a handler: - **One page, then return.** Never loop over every page inside one call; the cursor would be saved only at the end. - **Upsert, never insert.** A page can run twice after a crash (at least once, not exactly once). - **Read the window and the cursor from the job:** `WindowStart` and `WindowEnd` (`null` for a snapshot), `Cursor` (`null` on the first page). - **Put no credential in the cursor.** It is stored in the table. - **Draw a token before every request** when the API has a rate limit, with the same budget name everywhere that calls it, the web process included. - **Say what happened** with the three exceptions: `JobPostponedException` to wait without using an attempt, `JobThrottledException` when there is no budget, `JobAbandonedException` when a retry cannot help. Any other exception is a failure that is retried with backoff. - **Pass the cancellation token on**, and do not catch `OperationCanceledException`. - Each page runs in a fresh DI scope; scoped services are new for every page. **Done when** a unit test with a fake client shows: the first page reads `job.Cursor = null`, the last page returns `NextCursor = null`, a `429` throws `JobPostponedException`, and the same page written twice leaves one row. ### Step 4b. A recipe Write the recipe with `synclane init` from a curl that works, check it with `synclane test` (two pages, no database), and keep it in the project, for example `Sync/Recipes/orders.jsonc`. Then a credential store over the project's own storage: ```csharp public sealed class ShopCredentials(AppDb db) : ICredentialStore { public async ValueTask GetAsync(CredentialKey key, CancellationToken cancellationToken) { var shop = await db.Shops.FindAsync(new object[] { int.Parse(key.Owner) }, cancellationToken); return shop is { IsConnected: true } ? new Credential { Token = shop.AccessToken } : null; } public async ValueTask SaveRefreshTokenAsync(CredentialKey key, string refreshToken, CancellationToken cancellationToken) { var shop = await db.Shops.FindAsync(new object[] { int.Parse(key.Owner) }, cancellationToken); shop!.RefreshToken = refreshToken; await db.SaveChangesAsync(cancellationToken); } } ``` `null` means the owner has no credential any more and abandons the job (`SL5119`); an exception, such as a vault that cannot be reached, retries it. Register the recipe and say where its records go: ```csharp builder.Services.AddSyncLaneHttp(http => { http.Credentials(); http.Recipe("orders", File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Sync/Recipes/orders.jsonc"))) .WriteToPostgres("shop_orders", table => table.VersionedBy("$.updated_at")); }); ``` `WriteToPostgres` creates the table and upserts one row per owner and record. For the project's own tables, implement `IRecordSink` (one method, `WriteAsync(RecordPage page, ...)`), upsert there, and register it with `.WriteTo()` instead. **Done when** `synclane test Sync/Recipes/orders.jsonc` reads two pages and the application starts without a recipe error. ### Step 5. Declare the queue ```csharp builder.Services.AddSyncLane(builder.Configuration.GetSection("SyncLane"), lane => { lane.ConnectionString = builder.Configuration.GetConnectionString("Postgres")!; lane.AddBudget("shop-api", limit: 2, per: TimeSpan.FromSeconds(1), burst: 10); lane.AddQueue("shop.stores", queue => queue .Owners() .Windowed("orders", horizon: TimeSpan.FromDays(30), slice: TimeSpan.FromDays(7), every: TimeSpan.FromMinutes(15), overlap: TimeSpan.FromMinutes(10)) .Snapshot("products", every: TimeSpan.FromHours(6)) .Handle("invoice-upload")); }); ``` - A new queue's name starts with the application's name, so it cannot meet another application's on the schema. A queue that already runs keeps its name. - `Windowed`: history in slices back to `horizon`, newest first, then one job per `every` from where the data ends. - `Snapshot`: one job that reads everything, then one per `every`. - `Handle`: never planned; runs only when enqueued. - Each job type is a handler ([step 4a](#step-4a-a-handler)) or a recipe ([step 4b](#step-4b-a-recipe)), never both. A recipe's job type is declared with `HttpRecipeHandler` and has the recipe's name: `.Windowed("orders", ...)` for `http.Recipe("orders", ...)`. - Types run in the order they are declared, within a priority. - Declare the same budgets in every process that calls the API, the web process included. **Done when** the application starts, the log shows no `SL1xxx` error, the schema `synclane` exists with its tables, and `synclane.jobs` has rows for the owners from step 3. ### Step 6. Split the roles, if you chose to For the web and worker layout ([D2](#d2-which-process-does-what)), the same image runs twice, and only the worker has a role: ```yaml web: image: app worker: image: app environment: SyncLane__Role: "worker" ``` Before the first deploy with the split, set the two switches from the monitor. A switch can be set for an application and role that has not started yet, so neither container works where it should not, even for a moment: ```csharp await monitor.SetSwitchAsync("shop", role: null, runWorkers: false, runPlanner: false, reason: "web instances stay idle", by: user); await monitor.SetSwitchAsync("shop", role: "worker", runWorkers: true, runPlanner: true, reason: "the worker syncs", by: user); ``` Over HTTP: `POST /synclane/switch?application=shop&workers=false&planner=false&reason=web%20instances%20stay%20idle`, then `POST /synclane/switch?application=shop&role=worker&workers=true&planner=true&reason=the%20worker%20syncs`. The same call with `false` stops the worker later; its running jobs are handed back with their cursors. A new replica of either reads its switch when it starts, so scaling needs nothing more. See [Switching an application on and off](operations.md#switching-an-application-on-and-off). The switches live in the database of each environment: set them once in each (test, staging, production). Where none is set, both containers run workers, which is safe for the data but takes CPU from the web instances. Background services of the project that must run once, not in every web copy, belong to the worker too: register them only in the worker role. ```csharp if (builder.Configuration["SyncLane:Role"] == "worker") builder.Services.AddHostedService(); ``` **Done when** `GetSwitchesAsync()` shows the application's two rows, the worker role with its instances running workers and the planner and the web instances running neither, and jobs complete. ### Step 7. Health check and telemetry ```csharp builder.Services.AddHealthChecks().AddCheck("synclane"); app.MapHealthChecks("/health"); builder.Services.AddOpenTelemetry() .WithMetrics(metrics => metrics.AddMeter(SyncLaneTelemetry.MeterName)) .WithTracing(tracing => tracing.AddSource(SyncLaneTelemetry.ActivitySourceName)); ``` A worker without an HTTP port reports through its telemetry and its row in `synclane.instances`; give it a health endpoint only if the orchestrator needs one. Set the alerts listed in [Metrics and traces](operations.md#metrics-and-traces). **Done when** `/health` answers `Healthy` (or `Degraded` with a description you understand, such as polling behind a pooler). ### Step 8. The monitor over HTTP ```csharp app.MapSyncLane("/synclane").RequireAuthorization("ops"); ``` It answers only requests from the same machine until it requires authorization. Require it before anything else: the switches stop and start every application on the schema, not only this one. Every action (pause, requeue, skip, sync now) is logged with who and why. The routes are in [the package's readme](../src/SyncLane.AspNetCore/README.md); in code, inject `ISyncLaneMonitor` ([Watching it run](monitoring.md)). A screen of the project's own reads these calls, never SyncLane's tables with SQL of its own, which a SyncLane upgrade may change: each owner's jobs by status, for example, are `GetJobOwnersAsync` (`GET /synclane/jobs/owners?queues=shop.stores`). **Done when** `GET /synclane/overview` returns the queue with an authorized user, and is refused without one. ### Step 9. Refresh on demand and new accounts A "refresh" button or a webhook fetches from where the owner's data ends to now, at high priority. A burst of calls is one fetch, and the call returns at once; the worker does the work: ```csharp await monitor.SyncNowAsync("shop.stores", owner: shop.Id.ToString(), type: "orders", by: user.Id); ``` An account that just connected is planned now instead of at the next round: ```csharp await syncLane.PlanAsync("shop.stores", new JobOwner(shop.Id.ToString(), Name: shop.Name)); ``` "Connecting..." on screen needs no status column of the project's own: ```csharp var progress = await syncLane.GetProgressAsync("shop.stores", shop.Id.ToString()); ``` Work the project starts itself, such as an upload a user asked for, is a job of a type declared with `Handle`. Give it a `DedupKey` and what the handler must send as `Arguments`; the handler reads `job.Arguments`. Asked again under the same key, the job that is there takes the new request's place, so the latest one is what gets sent: ```csharp await syncLane.EnqueueOrReplaceAsync(new NewJob { Queue = "shop.stores", Owner = new JobOwner(shop.Id.ToString(), Name: shop.Name), Type = "invoice-upload", DedupKey = $"invoice:{invoice.Id}", Arguments = JsonSerializer.Serialize(invoice), RequestedBy = user.Id }); ``` When the upload got through some other way, close its job without running it: ```csharp await syncLane.CompleteAsync("shop.stores", shop.Id.ToString(), "invoice-upload", [$"invoice:{invoice.Id}"]); ``` Arguments hold no credential and are kept small: they are stored in the table ([Working with jobs](jobs.md#arguments)). Every call returns a result: check `Succeeded`, and map `Error.Kind` with `ToHttpStatusCode()` in an endpoint ([Working with jobs](jobs.md#results-and-errors)). **Done when** pressing the button creates one job, and pressing it five times quickly still creates one. ### Step 10. Accounts that disconnect or leave | Event | Call | | --- | --- | | Disconnected, may come back | Leave it out of the owner source, then `syncLane.CancelAsync(queue, owner, reason)`. When it comes back: `RequeueAsync(queue, owner)`; its slices continue from their cursors. | | Removed for good | Leave it out of the owner source, then `syncLane.ForgetOwnerAsync(queue, owner)`, then delete its data. | Never delete job rows by hand: the planner's summary would stay, and an owner that came back would never load its history again. **Done when** a disconnected test owner has no pending jobs, and a reconnected one continues. ### Step 11. Move from an existing sync If another system already loaded the history, record it so it is not fetched again. Mark only ranges without holes. 1. Switch the application off from the monitor (`SetSwitchAsync("shop", null, runWorkers: false, runPlanner: false, …)`), then deploy. 2. Call `syncLane.MarkLoadedAsync(queue, ranges)` with what the old system loaded ([Moving from another system](operations.md#moving-from-another-system)). 3. Stop the old system. 4. Switch the planner and the workers on. **Done when** the first jobs of a migrated owner cover only what is older than its marked range and what came after. ### Step 12. Deploy - **Schema:** with `CreateSchema = true` the first instance creates it and applies migrations behind a lock. With the project's own migrations, add `migrationBuilder.Sql(SyncLaneSchema.Script("synclane"))` now, and again in a new migration with each SyncLane upgrade that adds one ([Running the schema yourself](operations.md#running-the-schema-yourself)). - **Rolling deploys** are safe: migrations only add, and an older instance keeps working against the newer schema. - **Clocks:** keep the hosts' clocks in sync; leases and budgets use them. - **Connections:** each instance keeps one connection open to hear job changes, outside any pooler, from when its workers first wait for a job or something watches (a web instance whose workers are off opens none unless a live view reads it); and it takes connections from its pool only while a statement runs, rarely more than its busy slots plus a few for the planner, the heartbeat and the monitor. With many applications and replicas on one PostgreSQL, add them up, with the applications' own pools, against `max_connections`; cap SyncLane's pool with `Maximum Pool Size` in its connection string if you must, switch off what does not need to work, and switch off listening (`SetListeningAsync`) where polling every `PollInterval` is fast enough: that frees one connection per instance. **Done when** two copies of the worker run side by side for a day with every job created once and never two running jobs in one lane. ## 5. Prove it No page can promise that an integration works. These gates are how you know it does; the integration is done when every one of them has passed, with the evidence in the pull request. ### Tests - **The project's existing tests.** Run the whole suite before you start and keep the result. After the integration the same tests pass, unchanged. - **A unit test per handler:** the four cases of [step 4a](#step-4a-a-handler), and the rules from the inventory: the same input gives the same stored result as the old code did. - **One end-to-end test against a real PostgreSQL.** It runs the project's own registration with a fake API client and checks that the records arrive. A schema of its own per run keeps it apart from everything else. `WaitUntilAsync`, `CountOrdersAsync` and `DropSchemaAsync` are small helpers of the test project; `TestDatabase.ConnectionString` reads an environment variable, never a literal; `AddShopSync` is the same registration `Program.cs` calls; and the test database holds the shops the owner source returns: ```csharp [Fact] public async Task A_connected_shops_orders_reach_the_orders_table() { var schema = $"t_{Guid.NewGuid():N}"; var builder = Host.CreateApplicationBuilder(); builder.Configuration.AddInMemoryCollection(new Dictionary { ["ConnectionStrings:Postgres"] = TestDatabase.ConnectionString, ["SyncLane:Schema"] = schema, ["SyncLane:PlanInterval"] = "00:00:01", ["SyncLane:PollInterval"] = "00:00:01", }); builder.Services.AddShopSync(builder.Configuration); builder.Services.AddSingleton(new FakeShopClient(ordersPerPage: 100, pages: 3)); using var host = builder.Build(); await host.StartAsync(); var syncLane = host.Services.GetRequiredService(); await WaitUntilAsync(async () => { var all = await syncLane.GetJobsAsync(new JobQuery { Queue = "shop.stores", IncludeTotal = true }); var done = await syncLane.GetJobsAsync(new JobQuery { Queue = "shop.stores", Status = JobStatus.Completed, IncludeTotal = true }); return all.Total > 0 && done.Total == all.Total; }, timeout: TimeSpan.FromMinutes(1)); Assert.Equal(300, await CountOrdersAsync(shopId: TestShops.First)); await host.StopAsync(); await DropSchemaAsync(schema); } ``` - **SyncLane's own tests** (the lease, planning, rate budgets, crash recovery, on PostgreSQL 14 to 18 and through PgBouncer) run in SyncLane's repository for every release. The project does not copy them; it tests its use of SyncLane. ### The same data as before Run the new path beside the old one, as the [production trial](production-trial.md) describes: the old jobs write where they always did, the new handlers into a copy of the tables (or a staging database) for the same accounts. Then compare per account and day, both ways: ```sql SELECT shop_id, date_trunc('day', ordered_at) AS day, count(*) AS orders, md5(string_agg(external_id || ':' || net_total::text || ':' || status, ',' ORDER BY external_id)) AS fingerprint FROM orders GROUP BY 1, 2 EXCEPT SELECT shop_id, date_trunc('day', ordered_at), count(*), md5(string_agg(external_id || ':' || net_total::text || ':' || status, ',' ORDER BY external_id)) FROM orders_new GROUP BY 1, 2; ``` Run it again with the two tables swapped. Every row returned is a difference to explain before the cut-over. Count the side effects the same way: events published and emails sent per day, old and new. ### The first run ```sql SELECT type, status, count(*) FROM synclane.jobs GROUP BY type, status ORDER BY type, status; ``` - Jobs move from `pending` to `running` to `completed`; recent slices complete first. - `GetProblemsAsync()` is empty, or groups the failures by error code; [Error codes](errors.md) says what each means and how to fix it. - The project's tables fill, and running the same window again changes no row count. - `GetBudgetsAsync(new BudgetQuery())` shows each budget's rate; frequent `429`s mean the declared limit is too high. ### Done, and the cut-over The integration is done when all of these hold: - [ ] The build passes with no new warnings. - [ ] The existing tests pass, unchanged; the new unit tests and the end-to-end test pass. - [ ] The comparison returns no unexplained difference for 7 days in a row, side effects included. - [ ] `/health` is `Healthy`; no job is `abandoned` without a known cause. - [ ] The drills of the production trial behaved as expected. Then turn the old jobs off, keep their code for one more release in case you must turn them back on, and delete it in a later change. ## 6. Before production Run the [production trial](production-trial.md): one integration that is allowed to fail, slow settings, the old path beside it for two weeks, and the drills (graceful stop, `kill -9`, rolling deploy, two instances, provider outage, revoked access). ## 7. Upgrading an existing integration For a project that already runs SyncLane. The order matters more here than anywhere else on this page: the integration is live, and a change made in the wrong order shows at once in production. Read the project's SyncLane code and settings first, as [section 1](#1-what-the-project-does-today) reads its jobs, and write down what you find. ### What never changes in an upgrade | Do not change | Because | | --- | --- | | A queue's name | A queue of another name is a new queue: its owners' history is fetched again from the horizon, and the jobs of the old one wait with no worker. The rule that queue names start with the application's name is for new queues only. | | A job type's name | Each type keeps what it has loaded under its name; a new name loads it all again. | | An owner's key | The same: the owner's history loads again under the new key. | | A budget's name or key, without a reason | Its learned rate starts again from its declared limit. | ### Step U1. Find what the project has List, for every environment (test, staging, production) and every kind of container (web, worker): - the SyncLane packages and their version; - `Application`, `Role`, `RunWorkers`, `RunPlanner` and `ListenForChanges`, from `appsettings*.json`, from environment variables (`SyncLane__RunWorkers`, ...) and from the deployment files, with the value each kind of container ends up with; - the queues, job types and budgets the code declares. **Done when** the pull request has the table, one row per environment and kind of container. ### Step U2. Upgrade the packages Raise every SyncLane package to the same version. Read each version's **Changed** section in `CHANGELOG.md` between the old version and the new one: it lists what a project may have to change. The schema upgrades itself at start-up (with the project's own migrations, add `migrationBuilder.Sql(SyncLaneSchema.Script("synclane"))` in a new migration, [step 12](#step-12-deploy)). Change nothing else in this step. **Done when** the project builds, its tests pass unchanged, and the new version runs in test with the old settings, doing what it did before. ### Step U3. Name the application and its roles - **The name.** Set `SyncLane:Application` to the name the instances already register under (`GetInstancesAsync`), so that it is written down and nothing else changes. Choose a new one only when that name is shared with another application (`SharesNameWith`). To change it, switch the old name off first, `SetSwitchAsync(oldName, null, runWorkers: false, runPlanner: false, ...)` for each of its roles, then deploy the new name: instances that are switched off claim no queue, so the new ones start. Without that, a new instance that starts while one under the old name still runs the same queues is refused (`SL1011`), and a rolling deploy waits for it forever. - **The role.** Where one build runs as web and worker, add `SyncLane__Role=worker` to the worker's environment, and keep the old settings in place for now. **Done when** `GetInstancesAsync` shows every instance under the name and role you expect, all of them following switches (`FollowsSwitches`), and `GetSwitchesAsync` shows no instance ignoring them (`IgnoringSwitch` is 0). ### Step U4. Write the settings into switches, then remove the settings The settings still decide what each container does. Write the same decisions into switches, in each environment, before any setting is removed. A switch with the same values as the settings changes nothing at the moment it is set, so this step is safe while the old settings are still deployed: ```csharp await monitor.SetSwitchAsync("shop", role: null, runWorkers: false, runPlanner: false, reason: "web instances, as their settings said", by: user); await monitor.SetSwitchAsync("shop", role: "worker", runWorkers: true, runPlanner: true, reason: "the worker, as its settings said", by: user); await monitor.SetListeningAsync("shop", role: null, listen: false, reason: "behind the pooler, as its settings said", by: user); ``` Only for what the table of step U1 shows: a container whose settings leave `RunWorkers`, `RunPlanner` or `ListenForChanges` at `true` needs no switch for it. Over HTTP: `POST /synclane/switch` and `POST /synclane/switch/listen`, as in [step 6](#step-6-split-the-roles-if-you-chose-to). The switches are per environment; an AI assistant in the code cannot set them, and should not: it writes them into the pull request as a list for the people who run each environment, and the settings are removed only after that list is done. Then, in a deploy of its own, remove `RunWorkers`, `RunPlanner` and `ListenForChanges` from `appsettings*.json`, the environment variables and the deployment files. **Done when** `GetSwitchesAsync` shows, in every environment, each role running what it ran before the upgrade, and the settings hold none of the three. ### Step U5. Prove nothing changed The gates of [section 5](#5-prove-it), shorter: the project's tests pass unchanged; for a day after each step, the jobs created and completed per type, and the records written, match the days before; no job is `abandoned` without a known cause; `/health` is `Healthy`. ## Mistakes we have seen | Mistake | What happens | Instead | | --- | --- | --- | | An owner key that can change, such as a name | The owner's history loads again under the new key. | A stable id; the name goes in `JobOwner.Name`. | | Inserting records | A page that runs twice duplicates them. | Upsert by the record's id. | | A slice that takes hours for the biggest owner | A failure late in the slice repeats most of it. | A slice that finishes in minutes at the API's rate. | | Looping over all pages in one handler call | Nothing is saved until the end; a crash starts over. | Return after one page. | | A budget declared only in the worker | The web process's calls do not count against the limit. | The same `AddBudget` in every process that calls the API. | | Two applications running one queue | The second one is refused at start-up (`SL1011`). | One application per queue, its name starting with the application's. | | Two applications under the default name (`Api`) | One switch stops both; the monitor shows them as one; SyncLane warns (`SharesNameWith`, Degraded). | `SyncLane:Application`, a name of its own, in each. | | `RunWorkers: false` in `appsettings.json` to keep web instances idle | The decision is spread over every project and needs a deploy to change. | Leave it out; switch the web instances off from the monitor. | | `RunPlanner` off in every process | No jobs are created. | At least one process plans; `GetOverviewAsync` shows `Planners` per queue, and `GetSwitchesAsync` what each role runs. | | Renaming a queue or a job type in a running integration | The history of every owner is fetched again, and the old queue's jobs wait with no worker. | Keep the names; new names only for new queues ([section 7](#what-never-changes-in-an-upgrade)). | | Removing `RunWorkers: false` before the switches are set | The web instances start working at the next deploy. | Switches first, in every environment, then remove the setting ([step U4](#step-u4-write-the-settings-into-switches-then-remove-the-settings)). | | Renaming the application in a rolling deploy | The new instances are refused (`SL1011`) while the old ones run the queues, and the rollout never finishes. | Switch the old name off first ([step U3](#step-u3-name-the-application-and-its-roles)). | | Many applications and replicas on one PostgreSQL, connections never counted | `too many clients` when the last replica starts. | Count each instance's listening connection and pool against `max_connections` ([step 12](#step-12-deploy)). | | A job type declared with its own handler and also given a recipe | The application does not start (`SL5015`). | One or the other per job type; a recipe's type uses `HttpRecipeHandler`. | | Listening through PgBouncer in transaction mode | Live changes never arrive, and other clients see timeouts. | `ListenConnectionString` around the pooler, or listening switched off from the monitor (`SetListeningAsync`). | | Deleting job rows by hand | A returning owner never loads its history again. | `ForgetOwnerAsync`. | | Following this page over the project's own `CLAUDE.md` or `ARCHITECTURE.md` | The integration breaks the project's conventions. | The project's rules first; this page inside them. | | Copying a business rule into the handler | Two copies drift apart; the old and new data stop matching. | Call the service that holds the rule today. | | Editing an existing test so it passes | A change in behaviour goes unnoticed. | Find what the integration changed, and fix that. | | A token in a recipe, a test or `appsettings.json` | A secret in the repository. | `ICredentialStore`, or an environment variable while testing. | ## Checklist - [ ] The project's `CLAUDE.md`, `ARCHITECTURE.md` and similar rules are followed; every place this page gave way to them is listed in the pull request. - [ ] The code adds no comments, except those the project's rules require. - [ ] Today's behaviour is written down, one row per job, with the decision for each. - [ ] The questions in section 2 are answered, or their defaults written down. - [ ] SyncLane's code lives in one place, registered by one method. - [ ] Every business rule is called from where it lived before, not copied. - [ ] Owner keys are stable; owners that share a limit share a lane and a budget key. - [ ] Every write is an upsert; a page run twice changes nothing. - [ ] Each handler returns after one page, uses the job's window and cursor, and throws the right exception for `429` and revoked access. - [ ] Budgets are declared in every process that calls the API. - [ ] No credential in code, recipes, configuration files, tests or cursors. - [ ] `SyncLane:Application` is set to a name of its own, and every new queue's name starts with it; in an upgrade, the names it ran under are kept ([section 7](#7-upgrading-an-existing-integration)). - [ ] `RunWorkers`, `RunPlanner` and `ListenForChanges` are not in the settings; roles are set where one build runs as web and worker, and their switches are set in each environment; one process per container; at least one process plans. - [ ] Health check, telemetry and alerts are wired. - [ ] The monitor requires authorization. - [ ] Disconnect and removal call `CancelAsync` and `ForgetOwnerAsync`. - [ ] The existing tests pass unchanged; the handler tests and the end-to-end test pass. - [ ] The old and new data match for 7 days, side effects included. - [ ] The production trial has started. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/recipes.md # Recipes A recipe tells `SyncLane.Http` how to fetch one job type over HTTP: the request, how the job's window is written into it, and where the records are in the answer. It replaces a hand-written `IJobHandler` for APIs that fit it. > **Preview.** Recipes run, page, authenticate and keep to a rate budget, and have synced five public APIs, one per paging style ([samples/LiveCheck](../samples/LiveCheck)). They have not yet met the APIs of a production integration. ## Starting from a curl You rarely write a recipe from nothing. Copy a request that works, from the API's documentation, from Postman, or from the browser's developer tools ("Copy as cURL"), and put `synclane init` in front of it: ```bash synclane init curl 'https://api.example-shop.com/v2/orders?updated_after=2026-10-01T00:00:00Z&page=1&per_page=100' \ -H 'Authorization: Bearer ' ``` ```mermaid flowchart LR curl["A curl that works"] -->|"synclane init"| draft["orders.jsonc
a comment on every guess"] draft -->|"synclane test"| check["two pages, no database
structure, never data"] check -->|"fix and test again"| draft check -->|"ship it"| app["your app
http.Recipe(...)"] ai["your AI assistant
synclane mcp"] -.->|"the same steps, for you"| draft ``` `init` sends the request once and writes `orders.jsonc` from what the answer shows: - where the records are; - how to page: - a `Link` header; - a next URL; - a cursor, or `has_more` with the last record's id; - the page or offset already in the query; - which query values are the time window, and in which format; - the rate headers the API sends; - whether every record has a unique `id`, and which field carries its version. Each field it inferred has a comment above it saying why. Notes at the top say what is left for you, such as declaring the rate budget. The token in the curl is used for that one request and is written nowhere: the recipe's `auth` names a credential instead. To keep the token out of your shell history, pipe the curl in: `pbpaste | synclane init` on macOS, `Get-Clipboard | synclane init` in PowerShell. `init` never replaces a file unless you pass `--force`; `--out` names another file. A URL that redirects is refused, because recipes do not follow redirects; the message says what to use instead. Then run the recipe for two pages, without a database: ```bash synclane test orders.jsonc ``` ```text Testing example-shop/orders, from 2026-10-24 12:00 to 2026-10-31 12:00 UTC. Page 1 100 records 412 ms Page 2 100 records 380 ms Fields: id, number, status, updated_at, customer, lines, and 14 more Key: $.id, unique across 200 records. Paging: page 2 brought new records; more pages follow. The recipe works. ``` `test` runs the recipe through the same handler a job uses. **Credentials.** `test` reads the credential from the environment, or asks for it in the terminal without showing it. The variables are named after the credential: | Auth type | Variables (for a credential named `example-shop`) | | --- | --- | | bearer, API key | `SYNCLANE_EXAMPLE_SHOP_TOKEN` | | basic | `SYNCLANE_EXAMPLE_SHOP_USERNAME`, `SYNCLANE_EXAMPLE_SHOP_PASSWORD` | | OAuth 2.0 | `SYNCLANE_EXAMPLE_SHOP_CLIENT_ID`, `SYNCLANE_EXAMPLE_SHOP_CLIENT_SECRET`, `SYNCLANE_EXAMPLE_SHOP_REFRESH_TOKEN` | **Options:** - `--since` sets the window: a length such as `30d` or a date. The default is 7 days. - `--owner` gives the owner key to a recipe that uses `{{owner.key}}`. **What it prints:** field names, never their values. It never prints a cursor, a URL or a credential. **Exit code:** 1 when the recipe does not work, so the command also runs in CI. **A repeated page:** a page 2 that repeats page 1 fails the test with `SL6010`. It means the API ignored the paging parameter, and the message names that parameter. **Signed recipes:** a recipe that signs its requests with an `IRequestSigner` runs your code, which `test` cannot load. Test it from your application. The command is the `SyncLane.Cli` tool: `dotnet tool install --global SyncLane.Cli`. From a clone, `dotnet run --project src/SyncLane.Cli -- init ...` does the same. ## A recipe ```jsonc { "$schema": "https://raw.githubusercontent.com/synclane-dev/synclane/main/schemas/recipe.schema.json", "name": "example-shop/orders", "request": { "method": "GET", "url": "https://api.example-shop.com/v2/shops/{{owner.key}}/orders", "query": { "updated_after": "{{window.start}}", "updated_before": "{{window.end}}", "size": "200" }, "headers": { "Accept": "application/json" } }, "records": "$.content", "window": { "format": "iso8601" } } ``` The platform and endpoint above are made up; the format is real. Comments and trailing commas are allowed. A field the format does not know is an error, so a typo is caught instead of silently ignored. **`$schema` makes the editor help while you write.** It points at the recipe's JSON Schema, generated from the same types `HttpRecipe.Parse` reads, so it never disagrees with them. VS Code, Rider and Visual Studio then: - complete field names; - show each field's description on hover; - list the choices of fields such as `auth.type` or `pagination.type`, each with what it does; - underline a misspelt field before anything runs. Use the URL above, or a path to [schemas/recipe.schema.json](../schemas/recipe.schema.json) in a copy of the repository. The schema is also `HttpRecipe.JsonSchema`, for tools. It checks the shape; `Parse` still checks what a schema cannot, such as the URL's host or a placeholder's name. In VS Code, a recipe with comments is happiest as `jsonc`: name it `orders.jsonc`, or add `"files.associations": { "recipes/*.json": "jsonc" }`. Load it and see every problem at once: ```csharp var result = HttpRecipe.Parse(File.ReadAllText("recipes/orders.json")); if (!result.Succeeded) { foreach (var error in result.Errors) Console.WriteLine(error); // SL5004: Recipe 'example-shop/orders': request.query.from uses {{window.begin}}, ... return; } ``` The same recipe can be built in C#, as `new HttpRecipe { Name = ..., Request = new HttpRecipeRequest { ... } }`, and checked with `recipe.Validate()`. ## Running a recipe Declare the job type with `HttpRecipeHandler`, and register its recipe and where its records go ([Destinations](#destinations)): ```csharp builder.Services.AddSyncLane(lane => { lane.ConnectionString = builder.Configuration.GetConnectionString("Postgres")!; lane.AddQueue("shops", queue => { queue.Owners(); queue.Windowed("orders", horizon: TimeSpan.FromDays(365), slice: TimeSpan.FromDays(7), every: TimeSpan.FromMinutes(15)); }); }); builder.Services.AddSyncLaneHttp(http => { http.Recipe("orders", File.ReadAllText("recipes/orders.json")).WriteToPostgres("shop_orders"); }); ``` For a store of your own, a sink receives each page's records: ```csharp public sealed class OrderSink(AppDb db) : IRecordSink { public async Task WriteAsync(RecordPage page, CancellationToken cancellationToken) { foreach (var record in page.Records.EnumerateArray()) db.Orders.Upsert(page.Job.Owner, record); // a page can run twice: write with upserts await db.SaveChangesAsync(cancellationToken); } } ``` `page.Records` is only valid during the call; clone what you keep. For a quick start, `.WriteTo((page, cancellationToken) => ...)` takes a delegate instead of a class. Every problem is reported before anything runs. `AddSyncLaneHttp` throws one `SyncLaneException` holding every error of every recipe and setting. When the application starts, it compares recipes with the declared job types: a job type declared with `HttpRecipeHandler` and no recipe (`SL5014`), or a recipe for a type no queue declares (`SL5015`), stops it before any job runs. ### How answers become outcomes | Answer | Outcome | Code | | --- | --- | --- | | 2xx | Records go to the sink; the job completes. | | | 429 | The job waits for `Retry-After` (at most `MaxRetryAfter`), or for the reset the recipe's [rate headers](#reading-what-the-api-says) give (at least a second), or the queue's throttle delay, and continues. With a [rate budget](#rate-budgets), the whole budget pauses for everyone on the key, and the job waits as long as the pause. | `SL5105` | | 403 with `Retry-After`, or whose declared remaining header says 0 | The same as 429. Some APIs answer a spent limit with 403. | `SL5105` | | 429 or such a 403, with a rate budget | The job gives its slot back for the budget's pause without using an attempt: the budget keeps the API safe, and pacing is not failing. | `SL5105` | | A budget's token is further away than `MaxBudgetWait` | The job gives its slot back without using an attempt and runs again when the token is due. Nothing is sent. | `SL4003` | | 401 to an OAuth 2.0 token kept from an earlier page | The token is renewed once and the page sent again. | | | 401, any other 403 | The job is abandoned at once. The same credentials will not work on the next try. | `SL5106` | | 408, 5xx | Retried with the queue's growing delay. | `SL5107` | | No answer within `Timeout` | Retried. | `SL5108` | | DNS, connection, TLS or proxy failure | Retried. The message says which; the exception's own text is not kept. | `SL5109` | | 3xx | Abandoned. Redirects are not followed. | `SL5111` | | Other 4xx | Abandoned: retrying gets the same answer. | `SL5110` | | Larger than `MaxResponseBytes` | Abandoned. | `SL5112` | | Not valid JSON | Retried. | `SL5113` | | Nothing at the records path | Retried; some APIs answer 200 with an error now and then. | `SL5103`, `SL5104` | | No credential for the owner, or one that lacks a value | Abandoned before anything is sent. | `SL5119`, `SL5120` | | The token endpoint refuses, or answers without a usable token | Abandoned. | `SL5121`, `SL5123` | | The token endpoint answers 408, 429 or 5xx, times out or cannot be reached | Retried, or waits after 429. | `SL5122` | An abandoned job waits for you: fix the cause, then `RequeueAsync`. It continues from its cursor. ### Settings | Setting | Default | What it does | | --- | --- | --- | | `Timeout` | 100 seconds | How long one request may take, to the last byte of the answer: a page, or a token from a token endpoint. | | `MaxResponseBytes` | 16 MiB | The largest answer read. | | `MaxRetryAfter` | 1 hour | The longest wait taken from a `Retry-After` header. | | `MaxPagesPerJob` | 1,000 | The most pages one job reads with `page` or `offset` paging. | | `UserAgent` | `SyncLane.Http/` | Sent when a recipe sets no `User-Agent`. | The requests go through the named `HttpClient` `HttpSource.ClientName`. Add handlers to it with `services.AddHttpClient(HttpSource.ClientName)`, for a proxy for example. Do not add retry handlers: the engine already retries the job from its cursor. ## Destinations ### PostgreSQL ```csharp http.Recipe("orders", File.ReadAllText("recipes/orders.json")) .WriteToPostgres("shop_orders", table => table.VersionedBy("$.updated_at")); ``` SyncLane creates the table the first time a page arrives, in its own database and schema unless you name others, and keeps one row per account and record: | Column | What it holds | | --- | --- | | `owner`, `key` | The primary key: the account, and the record's key. Keys are unique per account, not across accounts. | | `record` | The latest copy of the record, as `jsonb`. | | `version` | The version it was written with, if the destination has one. | | `first_seen_at` | When the key first arrived. | | `changed_at` | When the record last changed. Writing the same record again does not touch the row. | Each page is one statement. A page is delivered at least once, since a worker that stops between the write and the cursor save writes it again, so the table is written so that a repeat changes nothing: - duplicates within a page are removed first; - a row is rewritten only when its record changed; - with a version, an older copy never replaces a newer one. | Setting | Default | What it does | | --- | --- | --- | | `KeyedBy("$.id")`, or several paths | `$.id`, inferred | What identifies a record. Paths are written `$.name` or `$.parent.name`; several make a composite key. | | `KeyedByContent()` | | Keys a record by a hash of its content, written in one canonical form. For records that never change, such as events or ledger lines: a record that changes becomes a new row with each version. | | `VersionedBy("$.updated_at")` | none | A number, or an ISO 8601 time; times in different offsets compare as the same moment, never as text. Of two copies the higher version wins; a copy without a version never replaces one with. | | `Schema` | SyncLane's schema | A lower-case identifier. | | `ConnectionString` | SyncLane's database | Another database. | **When no key is named,** `$.id` is used, but only if every record of the page has one that is a string or a number and no two are equal. A guess that could merge two records is never made: otherwise the job stops with `SL5125`, naming the fields of the page that could serve. **With `CreateSchema` off,** SyncLane does not create the table: run `PostgresSinkSchema.Script(schema, table)` in your own migration. A missing table stops the job with `SL5127`. ### HTTP ```csharp http.Recipe("orders", File.ReadAllText("recipes/orders.json")) .WriteToHttp("https://sync.example.com/orders", receiver => { receiver.Secret = builder.Configuration["Receiver:Secret"]; // whsec_…, to sign every request receiver.Headers["Authorization"] = builder.Configuration["Receiver:Token"]!; }); ``` Each page is posted as one JSON message: ```json { "type": "orders", "data": { "owner": "shop-7", "records": [ { "key": "1001", "version": 1793448000000000, "record": { } } ] } } ``` Keys and versions are read as for PostgreSQL: the same `KeyedBy`, `KeyedByContent` and `VersionedBy`, with the same `$.id` default. A version is a number; an ISO 8601 time arrives as microseconds since 1970, so the receiver compares numbers only. The requests follow [Standard Webhooks](https://www.standardwebhooks.com/), so a receiver can check them with an existing library: - `webhook-id`: the same records always give the same id, because the body holds no time. A page sent again carries the id it had; a page whose records changed carries a new one. The same value goes in `Idempotency-Key`. - `webhook-timestamp`: when it was sent. - `webhook-signature`: present when a secret is set. What SyncLane does with the answer: | Answer | What happens | | --- | --- | | 2xx | Taken. | | `413` | The request is split in halves until it fits. One record that still does not fit stops the job (`SL5130`). A page over `MaxBytes` (1 MB) is split before it is sent. | | `429`, `502`, `503`, `504` | Tried again in the page, honouring `Retry-After`; then, or straight away for a wait over 30 seconds, the job is postponed without using an attempt. | | Other 5xx, no answer in time, network failure | Tried three times with a short pause, without fetching the source again; then the attempt fails and the job runs again later (`SL5129`). | | A redirect, `410`, other 4xx | The job stops (`SL5128`): the receiver will keep refusing. Redirects are not followed. | **What the receiver does:** - Keep one row per `owner` and `key`, replacing it only when `version` is not lower. - Answer 2xx only once the records are stored. That is all it takes for every record to arrive once in effect: a message is sent again after anything goes wrong, and the key makes the repeat harmless. The URL, the headers and the secret are never logged; the URL must be https, except on `localhost`. ### A sink of your own Write an `IRecordSink`, and use `RecordIdentity` for the hard part. It reads keys and versions the same way, and removes duplicates within the page: ```csharp public sealed class OrderSink(AppDb db) : IRecordSink { private static readonly RecordIdentity Identity = RecordIdentity.ByPaths("$.id").VersionedBy("$.updated_at"); public async Task WriteAsync(RecordPage page, CancellationToken cancellationToken) { var records = Identity.Identify(page); if (!records.Succeeded) throw new JobAbandonedException(string.Join("; ", records.Errors)); foreach (var record in records.Value!) db.Orders.Upsert(page.Job.Owner, record.Key, record.Version, record.Record); // keep the newer version await db.SaveChangesAsync(cancellationToken); } } ``` Then check it the way workers will treat it, from any test framework: ```csharp var result = await SinkConformance.CheckAsync( new OrderSink(db), async (owner, cancellationToken) => await db.Orders.Where(order => order.Owner == owner) .Select(order => new SinkSample(order.Id, order.Total)).ToListAsync(cancellationToken), new SinkConformanceOptions { Versioned = true, Record = sample => $$"""{ "id": "{{sample.Id}}", "total": {{sample.Value}}, "updated_at": "{{sample.UpdatedAt:O}}" }""" }); Assert.True(result.Succeeded, string.Join("\n", result.Errors)); ``` It writes pages for owners made up for the run, and reads back what the store holds after each scenario: - a page written twice; - a page fetched again with one record changed and one added; - two copies of a record in one page; - an older copy after a newer one, when `Versioned`; - the same key under two owners; - an empty page. Each scenario the sink fails is in the result with code `SL5131`, naming what it found, for example "record 2 holds 1 instead of 2". `Record` turns a sample into the JSON your sink expects; leave it out for sinks that read `id`, `value` and `updated_at`. ## Pagination Add `pagination` when one request does not return everything. The job's cursor holds where paging stands, so a job that stops for any reason continues from the page it reached, not from the first. | Type | For APIs that | Fields | Last page | | --- | --- | --- | --- | | `page` | take a page number: `?page=3` | `param` (required), `start` (default 1), `size`, `sizeParam` | With `size`: the first page shorter than it. Without: the first empty page. | | `offset` | take a record offset: `?offset=200` | `param` (required), `size` (required), `start` (default 0), `sizeParam` | The first page shorter than `size`. | | `cursor` | return a token to send back: `?cursor=abc` | `param` (required); `from` (a path in the answer) or `fromLastRecord` (a property of the last record); `hasMore`, `size`, `sizeParam` | No token, or `hasMore` is `false`. | | `nextUrl` | return the next page's full URL in the body | `from` (required) | No URL. | | `linkHeader` | return it in a `Link` header with `rel="next"` | none | No `next` link. | ```jsonc // A page number and a page size: "pagination": { "type": "page", "param": "page", "size": 100, "sizeParam": "per_page" } // A cursor taken from the last record, stopping on a has-more flag: "pagination": { "type": "cursor", "param": "starting_after", "fromLastRecord": "id", "hasMore": "$.has_more" } // The next page's URL in the body: "pagination": { "type": "nextUrl", "from": "$.links.next" } ``` A field that does not apply to the type is an error (`SL5017`), as is a paging parameter that is also set in `request.query`. Paging is guarded against the usual ways it goes wrong: - **A host the recipe does not name.** A next URL, from the body, the `Link` header or a cursor someone edited in the table, must have the recipe's scheme, host and port. Otherwise it is not called and the job is abandoned (`SL5114`). Relative URLs are read against the request that returned them. - **A loop.** An answer that points to the page just read stops the job (`SL5117`). With `page` and `offset`, a job stops after `MaxPagesPerJob` pages (default 1,000; `SL5118`), which catches an API that ignores the page parameter. - **A change of recipe halfway.** A cursor the pagination cannot read abandons the job instead of guessing (`SL5115`). The next cursor is worked out before the sink runs, so a page whose next step cannot be followed is not written. With `nextUrl` and `linkHeader`, pages after the first are called exactly as the API wrote the URL; the recipe's `query` is not added again. Headers and body are sent with every page. Not supported yet: a page number, offset or cursor that the API expects in the body or in a header rather than in the query, as GraphQL APIs often do. Such APIs need a hand-written handler for now. ## Authentication A recipe names a credential; it never holds one. For every page, SyncLane asks your credential store for the values of the job's owner and adds them as the auth type says. ```jsonc "auth": { "type": "bearer", "credential": "example-shop" } ``` | `type` | What is sent | Values it needs | Other fields | | --- | --- | --- | --- | | `bearer` | `Authorization: Bearer ` | `Token` | | | `basic` | `Authorization: Basic`, user name and password in UTF-8 | `Username`, and `Password` if there is one | | | `apiKey` | The key in a header or a query parameter | `Token` | `name` (required); `in`: `header` (default) or `query`; `prefix` before a key in a header, such as `"Token "` | | `oauth2` | `Authorization: Bearer` with an access token from `tokenUrl`, or the token in the header `name` names | Client credentials: `ClientId`, `ClientSecret`. Refresh token: `ClientId`, `RefreshToken`, and `ClientSecret` if the client has one | `grant`: `clientCredentials` or `refreshToken` (required); `tokenUrl` (required); `scope`; `clientAuth`: `basic` (default) or `body`; `name`: a header for the token, for an API that does not take it in `Authorization`; `prefix` before it, none by default | | `signed` | Whatever your signer adds | Any, including `Values` | `signer` (required) | `credential` is required for every type. A field that does not apply to the type is an error, as with pagination. Prefer a header for an API key when the API accepts one: a URL is recorded in more places than a header, by proxies and by the API's own access logs. ### The credential store ```csharp builder.Services.AddSyncLaneHttp(http => { http.Credentials(); http.Recipe("orders", File.ReadAllText("recipes/orders.json")).WriteTo(); }); ``` ```csharp public sealed class ShopCredentials(AppDb db, Secrets secrets) : ICredentialStore { public async ValueTask GetAsync(CredentialKey key, CancellationToken cancellationToken) { var connection = await db.Connections.FindAsync([key.Owner, key.Name], cancellationToken); return connection is null ? null : new Credential { Token = secrets.Decrypt(connection.Token) }; } public async ValueTask SaveRefreshTokenAsync(CredentialKey key, string refreshToken, CancellationToken cancellationToken) { var connection = await db.Connections.FindAsync([key.Owner, key.Name], cancellationToken); connection!.RefreshToken = secrets.Encrypt(refreshToken); await db.SaveChangesAsync(cancellationToken); } } ``` - `key.Owner` is the job's owner; `key.Name` is the recipe's `credential`. Recipes for one account share a name. - Credentials stay where you keep them, encrypted as you choose. SyncLane stores none. - `GetAsync` is called once for every page and resolved from the page's scope, so a scoped database context works. Cache inside the store if a lookup is slow or rate limited. - Return `null` when the owner has no credential, for example after they disconnected: the job is abandoned with `SL5119`. Throw when the store cannot answer: the job is retried. - A recipe with `auth` and no registered store stops the application at start-up (`SL5020`). ### OAuth 2.0 - The access token is fetched when a page first needs it and kept in memory, one per owner and credential. It is renewed a minute before it expires (a tenth of its lifetime, for tokens that live less than ten minutes). Without `expires_in` it is kept until the API answers 401, and never longer than a day. - Pages that need a token at the same moment share one request to the token endpoint. - A 401 to a kept token renews it once and sends the page again. A 401 to a token fetched for that very page abandons the job. - When the token endpoint issues a new refresh token, `SaveRefreshTokenAsync` is called before the page goes on, with a token that is never cancelled: the old refresh token may already be retired. - With several instances, two may use the same rotating refresh token at once, and the slower one gets `invalid_grant`. SyncLane then reads the store once more and, if it holds a different refresh token, tries again with it. If the other instance has not saved yet, the job is abandoned with `SL5121` and a requeue fixes it. - Tokens are never written anywhere, so a restarted process fetches new ones. - Token requests go through the same `HttpClient`, so they never follow a redirect either. - Not supported: the authorization code flow itself, the consent screen where the owner grants access, which stays in your application (SyncLane starts from the refresh token it produced); the device flow; client authentication with a signed JWT or mutual TLS. Use a hand-written handler for those. ### Signed requests For APIs that want a signature, for example a hash of the method, path and time: ```csharp builder.Services.AddSyncLaneHttp(http => { http.Credentials(); http.Signer("example-hmac"); http.Recipe("orders", File.ReadAllText("recipes/orders.json")).WriteTo(); }); ``` ```csharp public sealed class ExampleHmacSigner(TimeProvider time) : IRequestSigner { public ValueTask SignAsync(HttpRequestMessage request, Credential credential, CancellationToken cancellationToken) { var timestamp = time.GetUtcNow().ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); var data = Encoding.UTF8.GetBytes($"{request.Method}\n{request.RequestUri!.PathAndQuery}\n{timestamp}"); var signature = Convert.ToHexString(HMACSHA256.HashData(Encoding.UTF8.GetBytes(credential.Values["secret"]), data)); request.Headers.Add("X-Timestamp", timestamp); request.Headers.Add("X-Signature", signature); return ValueTask.CompletedTask; } } ``` The recipe says `"auth": { "type": "signed", "credential": "example-shop", "signer": "example-hmac" }`. The signer sees the complete request: the URL with its paging parameters, the headers and the body. It may add headers and query parameters; changing the method, scheme, host or port abandons the job (`SL5124`), so a signer cannot send a request somewhere the recipe does not name. ### Where a credential never goes - **Into a recipe.** `Authorization` and `Proxy-Authorization` in `request.headers` are refused (`SL5019`). A recipe can be shared and committed. - **Into the jobs table.** Many APIs copy a query-string key into their next-page URLs. The key is taken out before the URL becomes the job's cursor, and added again when the page is requested. - **Into a message, a log or a span.** Messages name the credential and the missing value, such as "has no ClientSecret", never the value. A network error keeps only its kind, not the exception's text, which can hold the URL or a proxy's password. From a token endpoint's refusal, only a standard RFC 6749 code such as `invalid_grant` is quoted. - **To another host.** No redirects are followed, next-page URLs on another host are refused, and a signer cannot move the request. A test holds this: every type runs through the engine against an API and a token endpoint that echo every secret they receive in bodies and exception messages, and the test searches every log line, span, metric and database row for them. What it cannot cover is tracing of `HttpClient` itself, if you turn it on: a key in a query string is part of the URL there. One more thing SyncLane does not pretend: .NET cannot wipe a string from memory, so a credential lives in memory as long as the page that uses it. ## Rate budgets An API's limit belongs to an account. Declare it once in `AddSyncLane`, and name it in every recipe that calls the account: ```csharp lane.AddBudget("example-shop", limit: 2, per: TimeSpan.FromSeconds(1), burst: 40); ``` ```jsonc "rate": { "budget": "example-shop" } ``` | Field | Required | What it is | | --- | --- | --- | | `budget` | yes | The budget's name, as declared with `AddBudget`. A recipe naming an undeclared budget stops the application at start-up (`SL5023`). | | `key` | no | Whose bucket. Default `{{owner.key}}`: one bucket per owner. Write a fixed text, such as `"shared-account"`, for owners that share one set of credentials and so one limit, or one of the owner's values, such as `{{owner.seller}}`, for owners that share an account's limit: several stores of one seller account. Only the owner's key and values are allowed; a job whose owner lacks the value sends nothing (`SL5132`). | | `headers` | no | Where the API's answers say how many requests are left. See [Reading what the API says](#reading-what-the-api-says). | - Every request to the API waits for a token: the first request of a page, and the one sent again after an OAuth 2.0 token is renewed. Requests to a token endpoint do not draw from the budget. - A `429` pauses the budget for everyone on the key: for `Retry-After` when the API sent it, otherwise for one token's time, at least a second. After the pause the bucket refills from empty at 0.7 times its rate, and the rate climbs back while requests go through, never above the ceiling: the declared limit, or the one the API reports. The pause doubles, up to five minutes, only while the first request after each pause is refused again. A `429` for a request sent before the pause began does not count again, unless its `Retry-After` asks for longer. - A token further away than `MaxBudgetWait` (30 seconds) postpones the job: it gives its slot back without using an attempt. - Several recipes can name one budget: an account's limit is usually shared by all its endpoints. An API that limits each operation separately gets one budget per operation. - Buckets live in the database, so every instance draws from the same one. A `429` heard by one instance pauses the key on all of them: ```mermaid sequenceDiagram participant I1 as Instance 1 participant R as rate_buckets participant I2 as Instance 2 participant A as Their API I1->>R: take a token for the account I1->>A: request a page A-->>I1: 429, Retry-After: 20 I1->>R: pause the account's bucket for 20 s I2->>R: take a token for the account R-->>I2: paused for 20 s Note over I2: waits, or gives its slot back
when the wait is over MaxBudgetWait Note over R: after the pause: refill from empty
at 0.7× the rate, then climb back ``` - **Choosing the numbers.** Read the API's documentation for its algorithm and scope. - For a token or leaky bucket, set `limit` per `per` to its rate and `burst` to its bucket size. - For a window that resets on the clock, keep `burst` at 1, or name its headers. - When nothing is documented, declare a generous ceiling and a lower `start`, such as `AddBudget("example-shop", limit: 20, per: TimeSpan.FromSeconds(1), start: 0.25)`. The rate climbs while the API accepts and backs off when it refuses. - Learning needs requests to learn from: a few hundred. For an operation allowed once a minute, declare its documented rate. ### Reading what the API says Many APIs say on every answer how many requests are left, and when more come. Name those headers, and the budget stops at zero instead of running into a `429`, and notices when another app on the same account spends the same quota: ```jsonc "rate": { "budget": "example-shop", "headers": { "remaining": "X-Rate-Limit-Remaining", "reset": "X-Rate-Limit-Reset", "resetFormat": "seconds" } } ``` | Field | What it is | | --- | --- | | `headers.remaining` | The header with how many requests are left. | | `headers.remainingFormat` | `number` (default, such as `12`), `used/limit` (such as `32/40`: 8 left), or `ietf`: the `RateLimit` field of the IETF draft, such as `"default";r=50;t=30`, which carries its own window. | | `headers.reset` | The header with when more requests come. Not with `ietf`. | | `headers.resetFormat` | `seconds` from now (default), `unix` seconds, `unix-ms`, or `http-date`. Times are measured against the answer's `Date` header when it has one, so the API's clock and yours need not agree. | | `headers.limit` | The header with the API's limit, such as `X-Rate-Limit-Limit`. | | `headers.limitFormat` | `number` (default, such as `40`), or `ietf`: the `RateLimit-Policy` field of the IETF draft, such as `"default";q=100;w=60` (100 requests per 60 seconds). Of several policies the tightest counts. | | `headers.limitWindow` | The seconds the limit counts over, 1 to 86,400, from the API's documentation: `60` for "40 a minute", `1` for "0.5 a second". Required with `number`, since a bare number does not say its window. Not with `ietf`, which carries its own. | What SyncLane does with them: - **What is left only ever lowers.** The bucket drops to what the API says is left, minus the requests that took a token after the one answered and have not reached the API's count yet, on any instance. It never rises above the bucket's rate and burst. - **Nothing left and a reset known:** every request of the key waits for the reset, on every instance, and the bucket restarts empty. This is not a throttle: it does not lengthen later backoffs, and it is counted in `synclane.budget.exhausted`, not `synclane.budget.paused`. - **Nothing left, no reset:** the bucket empties and refills at its declared rate. - **The limit the API reports is the ceiling.** It takes the place of the declared limit, higher or lower, on every instance, from the next request, for as long as the API keeps reporting it. The rate climbs to a higher one as it learns; it does not jump. A value that repeats the known one writes nothing. An operator's temporary limit (`LimitBudgetAsync`) still holds below it. - **A value that cannot be read is ignored.** Nothing is read from a header the recipe does not name, the IETF ones included. Examples from public documentation. Check the API's own page: these change. | API | `headers` | | --- | --- | | ShipStation v1 | `{ "remaining": "X-Rate-Limit-Remaining", "reset": "X-Rate-Limit-Reset" }` | | GitHub | `{ "remaining": "x-ratelimit-remaining", "reset": "x-ratelimit-reset", "resetFormat": "unix" }` | | Walmart Marketplace | `{ "remaining": "x-current-token-count" }` | | Shopify REST Admin | `{ "remaining": "X-Shopify-Shop-Api-Call-Limit", "remainingFormat": "used/limit" }` | | ShipStation v1, with its limit | `{ "remaining": "X-Rate-Limit-Remaining", "reset": "X-Rate-Limit-Reset", "limit": "X-Rate-Limit-Limit", "limitWindow": 60 }` | | An API following the IETF draft | `{ "remaining": "RateLimit", "remainingFormat": "ietf", "limit": "RateLimit-Policy", "limitFormat": "ietf" }` | How far it goes: - **With a reset, a window is exact.** The run in the tests (four jobs, another app spending a quarter of every window) gets no `429`. - **Without a reset, the count fixes the bucket's level, not its rate.** If the declared rate is above what the API allows, `429`s become fewer but do not stop: in a measured run against a hidden limit of 6 a second with a budget of 8, they went from 12% of requests to 7 to 10%. The `429`s that remain lower the budget's learned rate, which is what brings them down. - **A burst larger than a window's quota still overshoots** after a pause. Declare a burst no larger than the quota. ## Fields | Field | Required | What it is | | --- | --- | --- | | `name` | yes | A name for messages and logs. | | `request.method` | no | `GET` (default) or `POST`. | | `request.url` | yes | Absolute `https` URL. Placeholders may appear in the path and the query, never in the scheme or port. The host is written out, or made from the owner's values when `request.hosts` lists where it may be. | | `request.hosts` | no | For a host made from the owner's values: every host it may be. See [A host per owner](#a-host-per-owner). | | `request.query` | no | Parameters added to the URL. Values are strings and may contain placeholders. | | `request.headers` | no | Request headers. Values may contain placeholders. `Host`, `Content-Length`, `Transfer-Encoding` and `Connection` cannot be set; `Authorization` and `Proxy-Authorization` are refused, because credentials never go in a recipe. | | `request.body` | no | A JSON body, for `POST` only. Placeholders are filled in string values. | | `request.allowHttp` | no | Allow a plain `http` URL, and a plain `http` token URL. For local test servers only. | | `records` | no | Where the array of records is in the answer: `$` (default) for the root, or `$.data.items`. Property names only. | | `window.format` | no | How `{{window.start}}` and `{{window.end}}` are written. Default `iso8601`. | | `pagination` | no | How to get the next page. See [Pagination](#pagination). | | `auth` | no | How requests are authenticated. See [Authentication](#authentication). | | `rate` | no | The rate budget the requests draw from. See [Rate budgets](#rate-budgets). | ## Placeholders | Placeholder | Value | | --- | --- | | `{{window.start}}` | Start of the job's window, in `window.format`. | | `{{window.end}}` | End of the job's window, in `window.format`. | | `{{owner.key}}` | The job's owner key. | | `{{owner.}}` | One of the owner's values, such as `{{owner.region}}`: what the owner source gave in `JobOwner.Values`. A job whose owner lacks it sends nothing (`SL5132`). | | `{{request.id}}` | A new UUID for every request, the same wherever it appears in that request: for APIs that want a correlation id per call. | A placeholder is a name and nothing more: no expressions, no filters, no nesting. Any other name is an error when the recipe is loaded. ### Values per owner Many APIs need more about an account than its key: the marketplace it sells on, its region, its store's id. The owner source gives them, beside the name: ```csharp new JobOwner(account.Id, Name: account.StoreName) { Values = new Dictionary { ["market"] = account.Market, ["region"] = account.Region } } ``` and the recipe writes them where the API wants them, as `{{owner.market}}`. They are kept with the owner, like its name, and come with every job a worker takes: no lookup per page. An owner given without values keeps the ones it had. Names are letters, digits and underscores, starting with a letter; `key` is taken (`SL3013`). Values are not secrets: they may land in a URL, which the API's logs record, and in a saved cursor. Credentials go in the credential store. Like names, values are never written to a log, a trace or a metric. `synclane test` takes them as `--value region=eu`. ### A host per owner Some APIs give each account its own host: one per region, or one per store. The host may then be made from the owner's values, if the recipe lists every host it may be: ```jsonc "request": { "url": "https://{{owner.endpoint}}/v1/orders", "hosts": ["api-na.example.com", "api-eu.example.com", "api-fe.example.com"] } ``` `*.` and a domain allows any one name under it, for a host per store: `"https://{{owner.shop}}.stores.example.com/v1/orders"` with `"hosts": ["*.stores.example.com"]`. It allows `acme.stores.example.com`, and neither `stores.example.com` nor `a.acme.stores.example.com`. - The host is checked on every request, a next page's included, before it is sent. One outside the list sends nothing and abandons the job (`SL5133`), so a wrong or hostile value can never send the request, or its credential, elsewhere. - A made host holds letters, digits, dots, hyphens and the owner's values only: no user name, no port, no window. The scheme and port stay written out. - A next page must stay on the very host the job's request went to, not only on one of the list. - A recipe that writes its host out cannot have `hosts`. A job without a window cannot run a recipe that uses `{{window.start}}` or `{{window.end}}` (`SL5101`). Declare such job types with `Windowed`. ## Window formats All formats are in UTC. | Format | Example | | --- | --- | | `iso8601` | `2026-10-01T00:00:00Z` | | `unix` | `1790812800` | | `unixMilliseconds` | `1790812800000` | | `date` | `2026-10-01`. Only for windows that start and end at midnight. | ## What a recipe can never do These are deliberate limits, checked when the recipe is loaded or the request is built: - **Call a host it does not name.** The scheme and port are fixed text, and so is the host, unless `request.hosts` lists every host it may be; then a host outside the list is never sent to. See [A host per owner](#a-host-per-owner). - **Hold a credential.** `https://user:password@host` and an `Authorization` header are refused. A recipe names a credential; the credential store gives its values. See [Authentication](#authentication). - **Inject into the request.** Placeholder values are percent-encoded in the URL and written as JSON strings in the body, so a value cannot add a parameter or change the shape of the body. A header that would contain a line break after filling is not sent. - **Put a secret into an error message.** Messages name the recipe and the field, never a header value, a credential, a URL or a response body. A network error keeps only its kind, never the exception's own text. - **Follow a redirect.** A redirect could send the recipe's headers, keys included, to another host. It abandons the job instead. - **Log its URLs.** The `HttpClient` loggers that would write each request's URL, owner key and query included, are removed. - **Decompress with anything but the standard.** Answers in gzip, deflate or brotli are accepted when the server offers them. There is no compression of SyncLane's own. Every error code is listed in [errors.md](errors.md#the-http-source). --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/schemas/recipe.schema.json ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://raw.githubusercontent.com/synclane-dev/synclane/main/schemas/recipe.schema.json", "title": "SyncLane HTTP recipe", "description": "How to fetch one job type over HTTP: the request, where the records are in the answer and how the job\u0027s window is written. Build it in code or load it from JSON with String); the format is described in docs/recipes.md.", "type": "object", "properties": { "$schema": { "description": "The JSON Schema the file follows. Ignored by SyncLane; lets editors check the file.", "type": "string" }, "name": { "description": "A name for messages and logs, such as \u0060example-shop/orders\u0060.", "type": "string" }, "request": { "description": "The request to send for each page.", "type": "object", "properties": { "method": { "description": "\u0060GET\u0060 or \u0060POST\u0060. Defaults to \u0060GET\u0060.", "type": "string" }, "url": { "description": "The absolute https URL. Placeholders may appear in the path and the query, and are escaped. The scheme and port are always written out. So is the host, unless Hosts lists where it may be: then it may be made from the owner, such as \u0060https://{{owner.endpoint}}/v1/orders\u0060.", "type": "string" }, "hosts": { "description": "For a host made from the owner\u0027s values: every host it may be, such as \u0060api-eu.example.com\u0060, or \u0060*.example.com\u0060 for any one name under a domain. A request to any other host is never sent. Leave it out when the URL names its host.", "type": "array", "items": { "type": "string" } }, "query": { "description": "Query parameters added to the URL. Values may contain placeholders and are escaped.", "type": "object", "additionalProperties": { "type": "string" } }, "headers": { "description": "Request headers. Values may contain placeholders. \u0060Authorization\u0060 and \u0060Proxy-Authorization\u0060 are refused: credentials go through Auth, never into a recipe.", "type": "object", "additionalProperties": { "type": "string" } }, "body": { "description": "A JSON body for POST. Placeholders are filled in string values only, and written as JSON strings, so a value can never change the shape of the body." }, "allowHttp": { "description": "Allow a plain http URL. Meant for local test servers; leave it off for real APIs.", "type": "boolean" } }, "required": [ "url" ], "additionalProperties": false }, "records": { "description": "Where the array of records is in the JSON answer: \u0060$\u0060 for the root, or \u0060$.data.items\u0060. Defaults to the root.", "type": "string" }, "window": { "description": "How the job\u0027s window is written into the request. Defaults to ISO 8601 in UTC.", "type": "object", "properties": { "format": { "description": "The format of \u0060{{window.start}}\u0060 and \u0060{{window.end}}\u0060. Always in UTC.", "enum": [ "iso8601", "unix", "unixMilliseconds", "date" ], "enumDescriptions": [ "\u00602026-10-30T12:00:00Z\u0060.", "Seconds since 1970-01-01, such as \u00601793361600\u0060.", "Milliseconds since 1970-01-01.", "The date only, \u00602026-10-30\u0060. Use it only when windows start and end at midnight." ] } }, "additionalProperties": false }, "pagination": { "description": "How to get the next page. Leave it out when one request returns everything.", "type": "object", "properties": { "type": { "description": "How the API pages.", "enum": [ "page", "offset", "cursor", "nextUrl", "linkHeader" ], "enumDescriptions": [ "A page number in a query parameter: 1, 2, 3.", "A record offset in a query parameter: 0, 100, 200.", "A token from the answer, sent back in a query parameter.", "The full URL of the next page, in the answer.", "The URL of the next page in the \u0060Link\u0060 header, with \u0060rel=\u0022next\u0022\u0060." ] }, "param": { "description": "The query parameter that carries the page number, the offset or the cursor.", "type": "string" }, "start": { "description": "The first page number (default 1) or the first offset (default 0).", "type": "integer" }, "size": { "description": "Records per page. With Page a shorter page is the last one, which saves a request; without it the last page is the first empty one. Required for Offset.", "type": "integer" }, "sizeParam": { "description": "A query parameter to send Size in, such as \u0060limit\u0060 or \u0060per_page\u0060.", "type": "string" }, "from": { "description": "For Cursor: where the next cursor is in the answer, such as \u0060$.meta.next\u0060. For NextUrl: where the next page\u0027s URL is, such as \u0060$.links.next\u0060.", "type": "string" }, "fromLastRecord": { "description": "For Cursor: take the cursor from this property of the page\u0027s last record instead, such as \u0060id\u0060.", "type": "string" }, "hasMore": { "description": "For Cursor: a boolean in the answer that is \u0060false\u0060 on the last page, such as \u0060$.has_more\u0060.", "type": "string" } }, "required": [ "type" ], "additionalProperties": false }, "auth": { "description": "How requests are authenticated. Leave it out for an open API. A recipe never holds a secret: it names the credential, and the ICredentialStore gives its values for each owner.", "type": "object", "properties": { "type": { "description": "The authentication scheme.", "enum": [ "bearer", "basic", "apiKey", "oauth2", "signed" ], "enumDescriptions": [ "\u0060Authorization: Bearer\u0060 with the credential\u0027s Token.", "\u0060Authorization: Basic\u0060 with the credential\u0027s user name and password.", "The credential\u0027s Token in a header or query parameter of the recipe\u0027s choice.", "An OAuth 2.0 access token, fetched from the token endpoint, kept in memory and renewed before it expires.", "Each request signed by an IRequestSigner you register." ] }, "credential": { "description": "The name the credential store finds the values under, together with the job\u0027s owner. Recipes for one account share a name, such as \u0060example-shop\u0060.", "type": "string" }, "in": { "description": "For ApiKey: where the key goes. Defaults to a header.", "enum": [ "header", "query" ], "enumDescriptions": [ "In a request header.", "In a query parameter. Prefer a header when the API accepts one: a URL is recorded in more places." ] }, "name": { "description": "For ApiKey: the header or query parameter that carries the key, such as \u0060X-Api-Key\u0060. For OAuth2: the header that carries the access token, for an API that does not take it in \u0060Authorization: Bearer\u0060, such as \u0060X-Access-Token\u0060.", "type": "string" }, "prefix": { "description": "For ApiKey in a header, or OAuth2 with Name: text written before the key or token, such as \u0060Token \u0060. Left out, nothing is.", "type": "string" }, "grant": { "description": "For OAuth2: how the access token is obtained.", "enum": [ "clientCredentials", "refreshToken" ], "enumDescriptions": [ "The client credentials grant: the client id and secret alone.", "The refresh token grant: a refresh token the owner granted, for example through a consent screen in your application." ] }, "tokenUrl": { "description": "For OAuth2: the absolute https URL of the token endpoint. No placeholders.", "type": "string" }, "scope": { "description": "For OAuth2: the scope to ask for, such as \u0060orders:read\u0060. Left out, none is sent.", "type": "string" }, "clientAuth": { "description": "For OAuth2: how the client id and secret reach the token endpoint. Defaults to Basic.", "enum": [ "basic", "body" ], "enumDescriptions": [ "In an \u0060Authorization: Basic\u0060 header, as RFC 6749 recommends.", "As \u0060client_id\u0060 and \u0060client_secret\u0060 in the form body, for endpoints that only accept that." ] }, "signer": { "description": "For Signed: the name the IRequestSigner was registered under.", "type": "string" } }, "required": [ "type", "credential" ], "additionalProperties": false }, "rate": { "description": "The rate budget the recipe\u0027s requests draw from. Leave it out to send as fast as the queue\u0027s concurrency allows, which is fine for an API without a limit and rarely anywhere else.", "type": "object", "properties": { "budget": { "description": "The budget\u0027s name, as declared with \u0060lane.AddBudget\u0060 in \u0060AddSyncLane\u0060.", "type": "string" }, "key": { "description": "Whose bucket. Defaults to \u0060{{owner.key}}\u0060, one bucket per owner. Write a fixed text, such as \u0060shared-account\u0060, for owners that share one set of credentials and so one limit, or one of the owner\u0027s values, such as \u0060{{owner.seller}}\u0060, for owners that share an account\u0027s limit.", "type": "string" }, "headers": { "description": "The headers in which the API says how many requests are left, when more come, and what its limit is. Leave it out when its answers say nothing. No header is read unless it is named here.", "type": "object", "properties": { "remaining": { "description": "The header with how many requests are left, such as \u0060X-Rate-Limit-Remaining\u0060.", "type": "string" }, "remainingFormat": { "description": "How Remaining is written. Defaults to Number.", "enum": [ "number", "used/limit", "ietf" ], "enumDescriptions": [ "A number, such as \u006012\u0060.", "Used of a limit, such as \u006032/40\u0060: 8 are left.", "The \u0060RateLimit\u0060 field of the IETF draft, such as \u0060\u0022default\u0022;r=50;t=30\u0060: 50 are left within the next 30 seconds. It carries its own window, so Reset stays empty." ] }, "reset": { "description": "The header with when more requests become available, such as \u0060X-Rate-Limit-Reset\u0060.", "type": "string" }, "resetFormat": { "description": "How Reset is written. Defaults to Seconds.", "enum": [ "seconds", "unix", "unix-ms", "http-date" ], "enumDescriptions": [ "Seconds from now, such as \u006041\u0060.", "A Unix time in seconds, such as \u00601793361600\u0060.", "A Unix time in milliseconds, such as \u00601793361600000\u0060.", "An HTTP date, such as \u0060Fri, 30 Oct 2026 12:00:00 GMT\u0060." ] }, "limit": { "description": "The header with the API\u0027s limit, such as \u0060X-Rate-Limit-Limit\u0060. While the API reports it, it is the budget\u0027s ceiling in place of the declared limit, up or down, on every instance.", "type": "string" }, "limitFormat": { "description": "How Limit is written. Defaults to Number.", "enum": [ "number", "ietf" ], "enumDescriptions": [ "A number of requests per LimitWindow, such as \u006040\u0060.", "The \u0060RateLimit-Policy\u0060 field of the IETF draft, such as \u0060\u0022default\u0022;q=100;w=60\u0060: 100 requests per 60 seconds. Of several policies the tightest counts." ] }, "limitWindow": { "description": "The window Limit counts over, in seconds, as the API\u0027s documentation states it: \u006060\u0060 for \u002240 a minute\u0022, \u00601\u0060 for \u00220.5 a second\u0022. Required with Number, since a bare number does not say its window; left out with Ietf, which carries its own.", "type": "integer" } }, "additionalProperties": false } }, "required": [ "budget" ], "additionalProperties": false } }, "required": [ "name", "request" ], "additionalProperties": false } ``` --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/ai.md # Writing recipes with an AI assistant An AI assistant can write a recipe for you from a curl that works. SyncLane gives it two things: - **[`llms.txt`](../llms.txt)**, at the root of the repository: a short summary and links to the recipe guide, the JSON Schema and the error catalog, in the format assistants read. Point any assistant at it, or at [`llms-full.txt`](../llms-full.txt), every page it links to in one file. Assistants that read documentation through [Context7](https://context7.com/) find the same pages as "SyncLane for .NET". - **`synclane mcp`**: the `synclane` command as tools the assistant can call, over the [Model Context Protocol](https://modelcontextprotocol.io/). The assistant drafts a recipe from your curl, checks it, and runs it for two pages, then fixes what the results say. The assistant runs where it already runs, with your own account. SyncLane calls no AI service, needs no key of ours and opens no port: the assistant starts `synclane mcp` on your machine and talks to it over standard input and output. ## Setting it up `synclane mcp` is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.synclane-dev/synclane`, and on nuget.org among [MCP servers](https://www.nuget.org/packages?packagetype=mcpserver), whose page for `SyncLane.Cli` gives the settings for VS Code and Visual Studio. With the .NET 10 SDK nothing needs installing: `dnx` fetches the package when the assistant starts it. ```json { "mcpServers": { "synclane": { "command": "dnx", "args": ["SyncLane.Cli", "--yes", "mcp"] } } } ``` Name a version, as in `"SyncLane.Cli@0.11.0"`, to keep every machine on the same one. To have the command in your terminal as well, install it once instead: ```bash dotnet tool install --global SyncLane.Cli ``` Then add it to your assistant's MCP settings. The server is the command `synclane` with the argument `mcp`. For example, in a project's `.mcp.json` (Claude Code), `.cursor/mcp.json` (Cursor) or Claude Desktop's settings: ```json { "mcpServers": { "synclane": { "command": "synclane", "args": ["mcp"] } } } ``` In VS Code, `.vscode/mcp.json`: ```json { "servers": { "synclane": { "type": "stdio", "command": "synclane", "args": ["mcp"] } } } ``` The tools read and write recipes only in the folder the assistant starts the server in, which is the open project for most editors. To work elsewhere, add `"--folder", "path/to/recipes"` to the arguments. ## The tools | Tool | What it does | Reaches the network | | --- | --- | --- | | `synclane_recipe_guide` | The [recipe guide](recipes.md), for the assistant to read first. | No | | `synclane_recipe_schema` | The recipe's JSON Schema, with every field described. | No | | `synclane_init` | `synclane init`: sends your curl once, writes a draft with a comment beside every guess, and returns it. | Yes, once, to the URL in the curl | | `synclane_check` | Reads a recipe file and names every problem with how to fix it. | No | | `synclane_test` | `synclane test`: runs the recipe for two pages without a database and reports the records' fields, whether the key is unique and whether paging works. A recipe that uses the owner's values (`{{owner.region}}`) takes them in `values`. | Yes, to the recipe's URL | | `synclane_explain_error` | What a code such as `SL5106` means and how to fix it. | No | The tools run the same code as the commands, so they return what the commands print and nothing more: field names, counts and comments, never a record, a cursor, a URL's key or a credential. Most assistants ask you before they call a tool that reaches the network. ## Keeping credentials out of the conversation A recipe never holds a credential; it names one, and your application supplies the value. When the assistant drafts and tests a recipe, the request needs the real value, and it should not pass through the conversation, where it would reach the assistant's provider. So put it in an environment variable of the server, and write `$NAME` in the curl: ```json { "mcpServers": { "synclane": { "command": "synclane", "args": ["mcp"], "env": { "SHOP_TOKEN": "${SHOP_TOKEN}" } } } } ``` ```text curl -H "Authorization: Bearer $SHOP_TOKEN" "https://api.example-shop.com/v1/orders?updated_since=2026-10-01" ``` `synclane_init` replaces `$SHOP_TOKEN` (or `${SHOP_TOKEN}`) with the variable's value when it sends the request, and the recipe it writes names a credential instead. `synclane_test` reads the credential from the variables named in its error (`SL6007`), such as `SYNCLANE_EXAMPLE_SHOP_TOKEN`; set those the same way. Whether `${SHOP_TOKEN}` in the settings is read from your shell depends on the assistant; where it is not, write the value there, and keep that file out of version control. If you paste a curl with the token in it into the conversation, the assistant's provider has the token. Revoke it and make a new one. ## Without MCP Any assistant can write a recipe from [`llms.txt`](../llms.txt) and the guide alone. Run `synclane init` and `synclane test` yourself and paste their output back: it holds no data and no credential, by design, so it is safe to share. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/errors.md # Error codes Every error SyncLane reports has a stable code. A code is never reused or renumbered, so it is safe to branch on, to alert on and to use as a localization key. The message that comes with it is English and may be reworded; the code does not change. The first digit is the area: | Range | Area | How it reaches you | | --- | --- | --- | | `SL1xxx` | Configuration | `SyncLaneException` from `AddSyncLane`, before the application starts. | | `SL2xxx` | Schema and stored data | `SyncLaneException` at start-up, or when a row cannot be read. | | `SL3xxx` | Calls to `ISyncLane` | A failed `SyncResult`, never an exception. | | `SL4xxx` | Running jobs | Text in the job's `error` column, starting with the code. | | `SL5xxx` | The HTTP source (`SyncLane.Http`) | `SL50xx`: a failed result when a recipe is loaded. `SL51xx`: a recipe that does not fit a job or a response, while running. | | `SL6xxx` | The `synclane` command (`SyncLane.Cli`) | A curl or a recipe the command cannot work with. | `SyncErrorCodes` and `HttpErrorCodes` hold every code as a constant. A test checks that each one is listed on this page. ## Configuration | Code | Kind | Cause | Fix | | --- | --- | --- | --- | | `SL1001` | Configuration | No connection string was set. | Set `options.ConnectionString`, for example from configuration. | | `SL1002` | Configuration | The schema name is not a plain lower-case identifier. It is placed into SQL as an identifier, so anything else is refused. | Use lower-case letters, digits and underscores, starting with a letter or underscore. | | `SL1003` | Configuration | `PlanInterval` or `PollInterval` is zero or negative. | Use a positive interval. | | `SL1004` | Configuration | Two queues have the same name. | Give each `AddQueue` call its own name. | | `SL1005` | Configuration | Two job types of one queue have the same name. | Give each type of a queue its own name. | | `SL1006` | Configuration | A queue setting cannot work, such as `Concurrency = 0` or a `RetryMaxDelay` below `RetryBaseDelay`. The message names the setting and the rule. | Change the setting as the message says. | | `SL1007` | Configuration | A job type setting cannot work, such as a zero `slice` or an `offset` longer than `every`. | Change the setting as the message says. | | `SL1008` | Configuration | A rate budget is declared twice with `AddBudget`. | Declare each budget once; every queue can draw from it. | | `SL1009` | Configuration | A rate budget's setting is out of range: the name, `limit` or `burst` below 1, or `per` not longer than zero. | Change the setting the message names. | | `SL1010` | Configuration | `options.Application`, or the host's application name it defaults to, is empty, longer than 100 characters, or holds a character other than letters, digits, dots, underscores, colons, slashes or hyphens. | Set `options.Application` to a name that fits. | | `SL1011` | Configuration | At start-up, a live instance of another application already runs a queue this one runs, with its planner or its workers. Two applications on one queue would take each other's jobs and abandon the types they do not know. The message names the queue, the application and the instance. | Rename the queue in one of the applications, or give both the same `options.Application` if they are one application. A stopped instance never counts; one that died without stopping stops counting two minutes after its last heartbeat. | | `SL1012` | Configuration | The section passed to `AddSyncLane(configuration, ...)` names a queue, job type or budget the code does not declare, or a setting SyncLane does not have there. Configuration overrides what the code declares and never adds to it. Names ignore case, as configuration keys do, unless the code declares two names that differ only in case. The message gives the full path and what can be set there. | Fix the name, or declare the queue, type or budget in code first. | | `SL1013` | Configuration | A value in that section cannot be read as what its setting takes: a whole number, a time span such as `00:15:00` or `7.00:00:00`, `true` or `false`, or a number such as `0.25`. The message names the path and the expected kind, never the value, which could be a connection string. | Fix the value, or remove it to keep what the code sets. | | `SL1014` | Configuration | `options.Role` (`SyncLane:Role` in configuration) is empty, longer than 100 characters, or holds a character other than letters, digits, dots, underscores, colons, slashes or hyphens. | Set it to a name that fits, such as `worker`, or leave it out. | ## Schema and stored data | Code | Kind | Cause | Fix | | --- | --- | --- | --- | | `SL2001` | Configuration | `CreateSchema` is off and the database lacks a migration this version needs. | Run `SyncLaneSchema.Script()` in your own migration, or turn `CreateSchema` on. | | `SL2002` | Internal | A row holds a status this version does not know. It was written by a newer version or by hand. | Run the same version on every instance, or correct the row. | | `SL2003` | Internal | A row holds a mode this version does not know. | The same as `SL2002`. | | `SL2004` | Internal | The row of a rate bucket was deleted while an instance was using it. | Do not delete rows from `rate_buckets` while instances run. A deleted row is created again, full, on next use; the job is retried. | ## Calls to ISyncLane | Code | Kind | Cause | Fix | | --- | --- | --- | --- | | `SL3001` | NotFound | The call names a queue that was not declared. | Declare the queue in `AddSyncLane`, or check the name. | | `SL3002` | NotFound | `EnqueueAsync` names a job type that is not declared on the queue. | Declare the type with `Snapshot`, `Windowed` or `Handle`. | | `SL3003` | Validation | `JobQuery.Limit` is below 1 or above `JobQuery.MaxLimit`. | Ask for a smaller page and follow `NextCursor`. | | `SL3004` | Validation | `JobQuery.Cursor` was not produced by SyncLane. | Pass the previous page's `NextCursor` unchanged. | | `SL3005` | Configuration | `RateBudgets.WaitAsync` or `Throttled` was called with a budget that is not declared. | Declare it with `lane.AddBudget(...)`, or correct the name. | | `SL3006` | Validation | `MarkLoadedAsync` was given a job type that is not declared with `Windowed`. A snapshot type reads everything on each run, so there is no history to mark. | Mark only windowed types; leave snapshot types to the planner. | | `SL3007` | Validation | A range given to `MarkLoadedAsync` starts after it ends, ends in the future, or, for a type without `every`, ends before today (UTC), which would leave the days after it unloaded for good. Nothing is marked. | Correct the range. For a type without `every`, mark history up to today. | | `SL3008` | NotFound | `RequeueJobAsync` or `RestartJobAsync` names a job that does not exist. Clean-up deletes completed jobs after `KeepCompletedJobs`, and `ForgetOwnerAsync` deletes an owner's jobs. | Check the id against `GetJobsAsync`. | | `SL3009` | Validation | `PauseAsync` was given an end (`until`) that is not after now. Nothing was paused. | Give a later end, or none to keep the pause until `ResumeAsync`. | | `SL3010` | Validation | `LimitBudgetAsync` was given a limit below 1, a period of zero or less, or an end (`until`) that is not after now. Nothing was changed. | Give at least 1 request per a positive period, and a later end or none. To lift a limit, use `ClearBudgetLimitAsync`. | | `SL3011` | Validation | `JobQuery.Search`, `FreshnessQuery.Search`, `FreshnessOwnerQuery.Search`, `JobOwnerQuery.Search`, `ActionQuery.Search` or `BudgetQuery.Search` is empty, only spaces, or longer than `JobQuery.MaxSearchLength` (100) characters. Nothing was read. | Search for part of an owner's key or name (of an action's text for `ActionQuery`, a budget's name or key for `BudgetQuery`), or leave `Search` out to list everything. | | `SL3012` | NotFound | `SyncNowAsync` was asked for an owner and job type that the queue has never planned, so there is no coverage to sync from. Nothing was created. | Check the queue, owner and type against `GetFreshnessAsync`. A new owner is planned by the application that runs the queue; call `PlanAsync` there, or wait for the next planning round. | | `SL3013` | Validation | An owner's `Values` hold a name that is not letters, digits and underscores starting with a letter, the name `key`, more than 20 values, or a value with a control character or over 1,000 characters. The message names the value, never shows it. `EnqueueAsync` and `PlanAsync` return it; a planning round that meets it fails and is tried again. | Fix the values where they are made: the owner source, or the `NewJob`'s owner. | | `SL3014` | Validation | `NewJob.RequestedBy` is longer than 200 characters or has a control character such as a line break. Nothing was enqueued. | Give a short identifier of who or what asked, such as a user's id or `scheduler`. | | `SL3015` | Validation | `SetSwitchAsync` (or `POST /switch`) was given an application or role that is not a usable name: empty, longer than 100 characters, or with a character other than letters, digits, dots, underscores, colons, slashes or hyphens. An empty role is allowed. Nothing was changed. | Give the application and role as the instances list shows them (`GetInstancesAsync`, `GET /instances`). | | `SL3016` | Validation | A read that groups owners across queues (`GetFreshnessOwnersAsync`, `GET /freshness/owners`, `GetJobOwnersAsync`, `GET /jobs/owners`) was given no `Queues`, or a queue name that is empty or only spaces. An owner is known by its key on one queue, so such a read needs to be told which queues share owner keys. Nothing was read. | Give the queues whose owners share keys, one or more, as `GetOverviewAsync` lists them (`?queues=a&queues=b` over HTTP). | | `SL3017` | Validation | `FreshnessOwnerQuery.StaleAfter` (or `staleAfter`) is zero or negative. Nothing was read. | Give a positive time, such as `1.00:00:00` for a day, or leave it out for the default of 24 hours. | | `SL3018` | Validation | `NewJob.Arguments` is longer than 262,144 characters or holds a null character. Nothing was enqueued. | Keep in the arguments only what the handler cannot look up, such as the body of a delivery, and let it read the rest by the job's owner and dedup key. | | `SL3101` | Conflict | `EnqueueAsync` found a job with the same owner, type and dedup key, or `EnqueueOrReplaceAsync` found a planned job with them. | Requeue the existing job, use another key, or call `EnqueueOrReplaceAsync` to let a job enqueued by hand take the new request's place. | | `SL3102` | Conflict | The job's status does not allow the action: a requeue takes failed, deferred and abandoned jobs, a restart takes any job that is not running. Nothing was changed. | Wait for a running job to end, or use the action that fits its status. | ## Running jobs These are written to the `error` column of the job, which ends `abandoned`. | Code | Kind | Cause | Fix | | --- | --- | --- | --- | | `SL4001` | Configuration | A worker took a job whose type has no handler in that process, usually because instances run different versions or configurations. | Declare the type on every instance that runs workers, then requeue. | | `SL4002` | Internal | The job was taken more often than its attempts allow without ever reporting a result. Its worker most likely dies while running it. | Look for crashes or out-of-memory kills during this job, fix them, then requeue. | | `SL4003` | Throttled | A request would have waited for a rate budget's token longer than `MaxBudgetWait`, so the job gave its slot back. The attempt does not count, the job keeps its cursor and runs again when the token is due. Written to the `error` column while the job waits. | Nothing, if it is rare. If it is common, the budget is smaller than the work: raise its limit if the API allows, or plan fewer jobs. | ## The HTTP source Recipes are checked when they are loaded, and every problem is reported at once. Messages name the recipe and the field, never a header value or a credential. | Code | Kind | Cause | Fix | | --- | --- | --- | --- | | `SL5001` | Validation | The recipe is not valid JSON, misses `name` or `request`, has a field the format does not know (often a typo), or a value of the wrong type. The message says which. | Correct the JSON; see [recipes.md](recipes.md). | | `SL5002` | Validation | A required field is empty, such as `name` or `request.url`. | Fill it in. | | `SL5003` | Validation | `request.url` is not absolute, does not use https, or contains a user name or password. | Use an absolute https URL. Put credentials in headers. Set `allowHttp` only for a local test server. | | `SL5004` | Validation | A placeholder names a value that does not exist. The message lists the ones that do. | Use `{{window.start}}`, `{{window.end}}` or `{{owner.key}}`. | | `SL5005` | Validation | A placeholder appears in the scheme, host or port of the URL, and the recipe lists no `request.hosts`. A recipe may only call the hosts it names. | Write the host out, and use the path or the query for values that change. For a host per owner, list every host it may be in `request.hosts` and make it from the owner's values. | | `SL5006` | Validation | `records` is not `$` or `$.name.name`. Filters, indexes and `..` are not supported. | Point the path at the array of records by property names. | | `SL5007` | Validation | `window.format` is not a known format. | Use `iso8601`, `unix`, `unixMilliseconds` or `date`. | | `SL5008` | Validation | `request.method` is not GET or POST. | Use GET or POST. | | `SL5009` | Validation | A header name is not an HTTP token, is one SyncLane sets itself (`Host`, `Content-Length`, `Transfer-Encoding`, `Connection`), or a value has a line break. | Correct or remove the header. | | `SL5010` | Validation | `request.body` is set on a GET. | Use POST, or remove the body. | | `SL5011` | Validation | A placeholder is unclosed or empty, such as `{{window.start` or `{{}}`. | Close it: `{{window.start}}`. | | `SL5012` | Configuration | A setting of `AddSyncLaneHttp` cannot work, such as a zero `Timeout`. | Change the setting as the message says. | | `SL5013` | Configuration | A recipe was registered without a sink. | Add `.WriteTo()` or `.WriteTo((page, cancellationToken) => ...)` after `Recipe(...)`. | | `SL5014` | Configuration | A job type runs with `HttpRecipeHandler` and has no recipe. Found at start-up, or by the handler if it runs outside a host. | Register a recipe for the type in `AddSyncLaneHttp`. | | `SL5015` | Configuration | A recipe is registered for a job type that no queue declares with `HttpRecipeHandler`, usually a typo. | Correct the type name on one side. | | `SL5016` | Configuration | Two recipes are registered for one job type. | Keep one. | | `SL5017` | Validation | The pagination cannot work as written: a required field is missing, a field does not apply to the type, a size or start is out of range, a path is not supported, or the paging parameter is also set in `request.query`. The message names the field. | Change the field as the message says; see the pagination types in [recipes.md](recipes.md#pagination). | | `SL5018` | Validation | The authentication cannot work as written: a required field is missing, a field does not apply to the type, the token URL is not an absolute https URL or has a placeholder, or the API key's name clashes with a header, query or paging parameter. The message names the field. | Change the field as the message says; see [Authentication](recipes.md#authentication). | | `SL5019` | Validation | `request.headers` sets `Authorization` or `Proxy-Authorization`. A recipe is meant to be shared and committed, so it never holds a credential. | Remove the header and use `auth`; the credential store gives the value for each owner. | | `SL5020` | Configuration | A recipe uses `auth` and no credential store is registered. | Add `http.Credentials()` with a class that implements `ICredentialStore`. | | `SL5021` | Configuration | A recipe has `auth.type` `signed` and names a signer that is not registered. | Add `http.Signer("name")` with a class that implements `IRequestSigner`, or correct `auth.signer`. | | `SL5022` | Validation | The recipe's `rate` cannot work as written: `budget` is not a valid name, or `key` is malformed or uses a placeholder other than `{{owner.key}}`. | Change the field as the message says; see [Rate budgets](recipes.md#rate-budgets). | | `SL5023` | Configuration | A recipe draws from a budget that is not declared. Found at start-up. | Add `lane.AddBudget("name", ...)` in `AddSyncLane`, or correct `rate.budget`. | | `SL5024` | Configuration | A Postgres destination's setting cannot work: the table or schema is not a lower-case identifier, the connection string is empty, or a key or version path is not written as `$.name`. | Correct the setting in `WriteToPostgres`. | | `SL5101` | Configuration | The recipe uses `{{window.start}}` or `{{window.end}}`, and the job has no window. | Declare the job type with `Windowed`, or remove the window placeholders. | | `SL5102` | Validation | A header would contain a line break once its placeholders were filled, usually from an owner key. The request is not sent. | Remove line breaks from the owner key. | | `SL5103` | Configuration | The response has nothing at the `records` path. | Compare the path with a real response. | | `SL5104` | Configuration | The `records` path leads to an object or a value, not an array. | Point the path at the list itself. | | `SL5105` | Throttled | The API answered 429, or 403 with `Retry-After` or with a declared remaining header of 0. The job waits for `Retry-After`, cut to `MaxRetryAfter`, or for the reset the recipe's rate headers give, or for the queue's throttle delay. With a rate budget the job is postponed for the budget's pause and the attempt does not count. | Nothing, unless it keeps happening: then lower `Concurrency` or widen `every`. | | `SL5106` | Unauthorized | The API answered 401, or 403 without a sign of a spent limit. The job is abandoned at once: the same credentials will not work on the next try. | Fix the owner's credentials, then requeue. | | `SL5107` | Unavailable | The API answered 408 or a 5xx status. The job is retried with the queue's growing delay. | Nothing, unless it keeps happening. | | `SL5108` | Unavailable | The API did not answer within `Timeout`. The job is retried. | Ask for smaller pages, or raise `Timeout`. | | `SL5109` | Unavailable | The API could not be reached. The message says what failed: the host name, the connection, TLS, the proxy, or the HTTP exchange. The exception's own message is not kept, because it may hold the URL or a proxy's password. The job is retried. | Check the host name, the network and the proxy. | | `SL5110` | Configuration | The API answered another 4xx, such as 400, 404 or 422. Retrying would get the same answer, so the job is abandoned. | Compare the recipe with the API's documentation, then requeue. | | `SL5111` | Configuration | The API answered with a redirect. SyncLane follows none, so a recipe only calls the host it names and headers never reach another host. | Put the final URL in the recipe. | | `SL5112` | Configuration | The response is larger than `MaxResponseBytes`. The job is abandoned. | Ask for smaller pages, or raise `MaxResponseBytes`. | | `SL5113` | Unavailable | The response is not valid JSON, often because it was cut off. The job is retried. The body is not quoted in the message. | Nothing, unless it keeps happening: then check what the API returns. | | `SL5114` | Configuration | The next page's URL, from the answer, the `Link` header or the job's cursor, points to another scheme, host or port. It is not called, so the recipe's headers never reach another host. The job is abandoned. | If the API really moves between hosts, write a recipe per host. | | `SL5115` | Configuration | The job's cursor is not one the recipe's pagination can read, usually because the pagination type changed while the job was halfway. | Clear the job's cursor and requeue it; it starts from the first page. | | `SL5116` | Configuration | The cursor, next URL or has-more flag in the answer has the wrong JSON type. | Compare the pagination paths with a real response. | | `SL5117` | Configuration | The answer points to the page that was just read. Following it would loop forever. | Check that the recipe sends the cursor in the parameter the API reads. | | `SL5118` | Configuration | A job reached `MaxPagesPerJob` pages with page or offset paging. The API may ignore the page parameter. | Check the parameter, cut smaller slices, or raise `MaxPagesPerJob`. | | `SL5119` | Unauthorized | The credential store returned no credential for the job's owner and the recipe's `auth.credential`. The job is abandoned. | Connect the owner's account, then requeue the job. | | `SL5120` | Configuration | The owner's credential lacks a value the auth type needs, such as `Token` for `bearer` or `ClientSecret` for client credentials, or holds one a header cannot carry, such as a line break. The message names the value, never shows it. The job is abandoned. | Fix the credential in the store, then requeue the job. | | `SL5121` | Unauthorized | The OAuth 2.0 token endpoint refused to issue a token (400, 401, 403 or another 4xx). The message adds the RFC 6749 error code, such as `invalid_grant`, when the endpoint gave one; nothing else from its answer. The job is abandoned. | Fix the client id, secret or refresh token, or the scope; for a revoked refresh token, have the owner connect again. Then requeue the job. | | `SL5122` | Unavailable | The OAuth 2.0 token endpoint answered 408, 429 or 5xx, did not answer within `Timeout`, or could not be reached. The job is retried; after 429 it waits as `Retry-After` asks. | Usually nothing; it passes. If it keeps happening, check `auth.tokenUrl` and the network. | | `SL5123` | Configuration | The token endpoint answered 2xx, but not with a usable bearer token: no `access_token`, a `token_type` other than bearer, a token a header cannot carry, an answer larger than 64 KiB or not JSON. The job is abandoned. | Check `auth.tokenUrl` and `auth.grant` against the API's documentation. | | `SL5124` | Configuration | An `IRequestSigner` changed the method, scheme, host or port of the request. The request was not sent and the job is abandoned. | Change the signer to add headers or query parameters only. | | `SL5125` | Validation | A record has no value its destination can key it by: the key is missing, not a string or a number, or, for the inferred `$.id`, not unique in the page. The message lists fields that could serve. Nothing of the page is written. | Name the key with `KeyedBy(...)`, or use `KeyedByContent()` for records that never change; then requeue. | | `SL5126` | Validation | A record's version is neither a number nor an ISO 8601 time, so an older copy could not be told from a newer one. Nothing of the page is written. | Name another field with `VersionedBy(...)`, or leave the version out; then requeue. | | `SL5127` | Configuration | A destination table does not exist, and `CreateSchema` is off, so SyncLane does not create it. | Run `PostgresSinkSchema.Script(schema, table)` in your own migration, or turn `CreateSchema` on; then requeue. | | `SL5128` | Validation | An HTTP destination refused a page and will keep refusing: it answered with a redirect (not followed), `410` (endpoint gone) or another 4xx. | Fix the receiver, the URL or the configured headers; then requeue. | | `SL5129` | Unavailable | An HTTP destination did not take a page after three tries: a 5xx, a timeout or a network failure. When it kept asking to slow down (`429`, `502`, `503`, `504`), the job is postponed without using an attempt. | Nothing, unless it lasts: then check the receiver. The job runs again from the same page. | | `SL5130` | Validation | A single record is larger than an HTTP destination accepts: it answered `413` for that record alone, or the record is over `MaxBytes`. | Raise the receiver's limit or `MaxBytes`; then requeue. | | `SL5131` | Validation | A sink failed a scenario of `SinkConformance.CheckAsync`: a page written again, a page with changed records, duplicates in a page, an older copy after a newer one, or the same key under two owners left the wrong records stored. Reported by the check, never at run time. | Write by key (`RecordIdentity` helps), replace a record only with a version that is not lower, and keep owners apart. | | `SL5132` | Configuration | The recipe uses `{{owner.}}` and the job's owner has no value of that name. Nothing was sent; the job is abandoned. The message names the value, never shows another. | Give the owner the value in `JobOwner.Values` from the owner source, then requeue the job. | | `SL5133` | Configuration | The host made from the owner's values is not in the recipe's `request.hosts`, or is not a host name at all, for example a value with a `/`, `@` or `:`. Nothing was sent; the job is abandoned. | Correct the owner's value. If the API really uses that host, add it to `request.hosts`. | ## Errors that are not on this page - **Exceptions your handler throws** are stored in the `error` column as they are, type and message, and drive the retry policy. They have no SyncLane code. - **A `null` argument** throws `ArgumentNullException`. It is a bug in the calling code, not a condition to handle. - **A database that cannot be reached** throws the `NpgsqlException` that Npgsql raised. Inside a worker it ends the attempt and the job is retried. - **Cancellation** throws `OperationCanceledException`. It is never reported as a failure. ## The synclane command | Code | Kind | What happened | What to do | | --- | --- | --- | --- | | `SL6001` | Validation | `synclane init` got no curl command with an http or https URL. | Type `synclane init` and paste the curl after it, as copied from the documentation or the browser's "Copy as cURL"; or pipe it in: `pbpaste \| synclane init`. | | `SL6002` | Unavailable | The API refused the request of the curl given to `synclane init`, so there was no answer to learn from. The message says what the status usually means; a redirect is refused because recipes do not follow redirects. | Run the curl itself; copy a fresh one if the credential expired; for a redirect, put the address it redirects to in the curl. | | `SL6003` | Validation | The API answered the curl's request with something that is not JSON. | Ask for JSON, for example with `-H 'Accept: application/json'`. | | `SL6004` | Unavailable | The curl's request did not reach the API: the host name, the connection or TLS failed, or no answer came in time. The message names which, never the URL. | Check the URL and the connection; run the curl itself. | | `SL6005` | Conflict | The file `synclane init` would write exists already. | Name another file with `--out`, or pass `--force` to replace it. | | `SL6006` | NotFound | There is no recipe file at the path given to `synclane test`. | Give the path of a recipe file. | | `SL6007` | Configuration | The recipe needs a credential, it is not in the environment, and there is no terminal to ask for it in (as in CI). | Set the variables the message names: `SYNCLANE__TOKEN`, or `_USERNAME`/`_PASSWORD`, or `_CLIENT_ID`/`_CLIENT_SECRET`/`_REFRESH_TOKEN`. | | `SL6008` | Configuration | The recipe signs its requests with an `IRequestSigner` of your application, which `synclane test` cannot load. | Run the job from your application, for example with `EnqueueAsync` and a test owner. | | `SL6009` | Validation | The recipe uses the owner's values (`{{owner.key}}`), and no owner was given. | Pass `--owner` with the key of an owner to test with. | | `SL6010` | Validation | Page 2 brought the same records as page 1: the API did not read the paging parameter the recipe sends. The test fails. | Check the parameter's name in the API's documentation, correct the recipe's `pagination`, and test again. | | `SL6011` | Validation | The value of `--since` is neither a length of time nor a date. | Give a length such as `7d`, `12h` or `30m`, or a date such as `2026-10-01`. | | `SL6012` | Validation | A tool of `synclane mcp` was given a file outside the folder the server was started in. The tools read and write recipes only there, so an assistant cannot be talked into touching other files. Nothing was read or written. | Give a path inside that folder, or start `synclane mcp` in the folder that holds the recipes (most assistants start it in the open project). | | `SL6013` | Validation | The folder given to `synclane mcp --folder` does not exist. The server did not start. | Give the path of an existing folder, relative to where the assistant starts the server or absolute, or leave `--folder` out. | | `SL6014` | Validation | The recipe uses values of the owner (`{{owner.marketplaceId}}` and the like), and `synclane test` was not given them. Nothing was sent. | Pass each as `--value name=value`; the message lists the names. In `synclane mcp`, give them in the test tool's `values`. | ## The HTTP endpoints Codes of `SyncLane.AspNetCore`. They come back as problem details, with the code as `title` and in `code`. | Code | Kind | What happened | What to do | | --- | --- | --- | --- | | `SL7001` | Unauthorized | A request from another machine reached endpoints mapped by `MapSyncLane` that do not require authorization. They answer only local requests until they do, and a request that came through a proxy is not local. The answer is 403. | Add `.RequireAuthorization(...)` to `MapSyncLane(...)`, with the policy your operators sign in with. | | `SL7002` | Validation | A repair was posted without the `X-SyncLane-Action` header. The header shows the request came from your own script or page: another site cannot make a browser send it. | Send the header with any value. | --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/src/SyncLane.Cli/README.md # synclane Turns a curl that works into a SyncLane recipe, and tests the recipe without a database. ```bash dotnet tool install --global SyncLane.Cli ``` ## From a curl to a recipe Copy a request from the API's documentation or your browser and paste it after `synclane init`: ```bash synclane init curl "https://api.example-shop.com/v1/orders?updated_since=2026-10-01" \ -H "Authorization: Bearer $SHOP_TOKEN" ``` `init` sends the request once and writes `orders.jsonc` from the answer: - where the records are; - how the API pages; - which parameter takes the time window; - which headers say how many requests are left. Every guess carries a comment that says why. The token in the curl is never written: the recipe names a credential instead. ## Testing a recipe ```bash synclane test orders.jsonc ``` `test` runs the recipe for two pages through the same code your application uses, with no database. It reports: - the fields it found; - whether the record key is unique; - whether page 2 brought new records. It never prints record values, cursors or credentials. It exits with 1 when the recipe does not work, so it can run in CI. Credentials come from environment variables such as `SYNCLANE_EXAMPLE_SHOP_TOKEN`, or from a prompt that does not echo. ## With an AI assistant `synclane mcp` serves `init`, `test` and a recipe check to an AI assistant over the Model Context Protocol, with the recipe guide, the JSON Schema and the error catalog. Add it to the assistant's MCP settings: ```json { "mcpServers": { "synclane": { "command": "synclane", "args": ["mcp"] } } } ``` With the .NET 10 SDK it runs without installing anything, as `"command": "dnx", "args": ["SyncLane.Cli", "--yes", "mcp"]`. It is listed in the MCP Registry as `io.github.synclane-dev/synclane`, and the "MCP Server" tab of this page gives the settings for VS Code and Visual Studio. It runs on your machine with your own assistant: no AI service is called and no port is opened. The tools work only in the folder the server starts in (or `--folder`), and return what the commands print: structure, never data or credentials. Write a token as `$NAME` in the curl and set the variable in the server's environment, so it never enters the conversation. Setup for several assistants: [docs/ai.md](https://github.com/synclane-dev/synclane/blob/main/docs/ai.md). ## More - Recipes, credentials and every option: [docs/recipes.md](https://github.com/synclane-dev/synclane/blob/main/docs/recipes.md) - For AI assistants: [llms.txt](https://github.com/synclane-dev/synclane/blob/main/llms.txt) - Error codes `SL6xxx`: [docs/errors.md](https://github.com/synclane-dev/synclane/blob/main/docs/errors.md#the-synclane-command) - The library the recipes run in: [SyncLane](https://www.nuget.org/packages/SyncLane) --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/README.md

SyncLane

# SyncLane [![CI](https://github.com/synclane-dev/synclane/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/synclane-dev/synclane/actions/workflows/ci.yml) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) [![.NET 10](https://img.shields.io/badge/.NET-10-512BD4.svg)](https://dotnet.microsoft.com/) [![Tested on PostgreSQL 14 to 18](https://img.shields.io/badge/tested%20on-PostgreSQL%2014%E2%80%9318-336791.svg)](.github/workflows/ci.yml) [![SyncLane MCP server on Glama](https://glama.ai/mcp/servers/synclane-dev/synclane/badges/score.svg)](https://glama.ai/mcp/servers/synclane-dev/synclane) **Sync jobs against other people's APIs, from one PostgreSQL table you own.** Every job is a row: its window, its cursor, its attempts, its error. If your application pulls orders, products or anything else from an external API for many accounts, it needs the same things every time: load two years of history in slices, pick up what is new every few minutes, continue after a crash instead of starting over, back off when the other side says "slow down", never hit one account's limit from two workers at once, and send data back in order. SyncLane is a .NET library that does exactly that, inside your process, with no dependency beyond Npgsql and the `Microsoft.Extensions` abstractions. ![SyncLane's architecture: the PostgreSQL schema with the jobs table and the indexes that carry the guarantees; the planner, lease, page loop, failure policy, rate budgets, change feed, instances and monitor inside your application; the recipe pipeline of SyncLane.Http; their APIs and your tables; and what it promises.](https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/images/architecture.png) How a job runs, from the planner to a saved cursor and every way back when something fails ([How it works](docs/how-it-works.md) says it in words): ![How a job runs: plan, take, run a page, save the cursor and complete; a failed page waits and continues from its cursor, steps aside after the fifth try and waits for an operator after one more; a worker that stops hands its job back, one that dies loses it to another slot when the lease runs out; and a 429 pauses the account's budget for every instance.](https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/images/how-it-works.png) ## Why Hangfire, Quartz and the like are good at "run this method at that time". A sync job is a different animal. It has a range of time it covers, a position inside that range, and a neighbour it must not overlap with. When you put that on top of a general scheduler, the interesting state ends up somewhere you cannot see: in serialized arguments, in a second table of your own, or in a lock. SyncLane keeps that state where you can read and change it: - **A window on every job.** History is cut into slices; each slice is a job with a start and an end. What is new gets a window that starts where the last one ended. - **A cursor on every job.** It is saved after each page. A job that fails, is redeployed or loses its worker continues from its last page. - **Lanes.** Jobs of one account run one after the other; accounts run side by side. - **Rate budgets.** Requests to one account go out at the pace you declare, shared by every job and queue that calls it. When the API says "slow down", every job on that account waits, not only the one that heard it. - **Planning that can be repeated.** The planner compares what should exist with what exists and adds the difference. Calling it a thousand times changes nothing. Raising the history from 60 days to two years fills only the gap. - **A row you can act on.** `status`, `attempt_count`, `error`, `next_run_at`, `leased_by`. If something is stuck, `SELECT` tells you why and `UPDATE` fixes it. ## What it aims to be SyncLane does not try to be a scheduler, a workflow engine or a data platform. Hangfire, Quartz and cron services run anything on time, and they do it well. SyncLane aims to be the small, dependable piece you add when your application pulls data from someone else's API: - **Quick to connect.** A package, a connection string, an owner source, and a handler or a recipe. Every other setting has a default you can leave alone. - **Compact.** A library inside your process. PostgreSQL is all it needs: no broker, no extra service, no dashboard to host. - **It takes the hard parts on itself.** Slicing history, resuming from the last page, retries, an account's rate limit shared by every instance and learned from its answers, delivering in order, and fencing out a worker that lost its lease. Your code handles one page. - **Safe by default.** It stores no credential, and logs no header, body or cursor. It calls no host of its own: no telemetry, no license check, no update check. - **Open.** Apache 2.0, free, with no registration and no paid edition. ## Quick start ```bash dotnet add package SyncLane dotnet add package SyncLane.Http # recipes instead of handlers dotnet tool install --global SyncLane.Cli # synclane init, test and mcp ``` ### With a recipe For an API that lists JSON records page by page, you write no request code. Give your AI assistant `synclane mcp` and a curl that works, and it writes the recipe, checks it and runs it for two pages ([docs/ai.md](docs/ai.md)); or run `synclane init` and `synclane test` yourself ([docs/recipes.md](docs/recipes.md#starting-from-a-curl)). Then: ```csharp builder.Services.AddSyncLane(lane => { lane.ConnectionString = builder.Configuration.GetConnectionString("Postgres")!; lane.AddQueue("shops", queue => { queue.Owners(); queue.Windowed("orders", horizon: TimeSpan.FromDays(365), slice: TimeSpan.FromDays(7), every: TimeSpan.FromMinutes(15)); }); }); builder.Services.AddSyncLaneHttp(http => { http.Credentials(); // your ICredentialStore: credentials stay in your own storage http.Recipe("orders", File.ReadAllText("recipes/orders.jsonc")) .WriteToPostgres("shop_orders", table => table.VersionedBy("$.updated_at")); }); ``` `WriteToPostgres` creates the table and keeps one row per account and record; a page that runs twice changes nothing. Your own tables take an `IRecordSink`. Paging, OAuth 2.0 and other auth, rate limits, retries and resuming are the recipe's and SyncLane's job. ### With a handler For anything a recipe does not cover (multi-step reports, GraphQL, your own client), a handler does one page and says where the next one starts: ```csharp lane.AddQueue("shops", queue => { queue.Owners(); queue.Windowed("orders", horizon: TimeSpan.FromDays(730), slice: TimeSpan.FromDays(30), every: TimeSpan.FromMinutes(15)); }); public sealed class OrderHandler(ShopApi api, OrderStore store) : IJobHandler { public async Task RunPageAsync(Job job, CancellationToken cancellationToken) { var page = await api.GetOrdersAsync(job.Owner, job.WindowStart, job.WindowEnd, job.Cursor, cancellationToken); await store.UpsertAsync(page.Orders, cancellationToken); return new JobPage(page.NextCursor, page.Orders.Count); } } ``` ### Either way, an owner source It tells the planner who is connected. The key never changes; the lane groups owners that share a rate limit; the name is what the monitor shows and searches. ```csharp public sealed class ConnectedShops(AppDb db) : IOwnerSource { public async Task> GetOwnersAsync(string queue, CancellationToken cancellationToken) => await db.Shops.Where(shop => shop.IsConnected) .Select(shop => new JobOwner(shop.Id.ToString(), shop.SellerId, shop.Name)) .ToListAsync(cancellationToken); } ``` That is the whole integration. The table is created at start-up, the planner runs once a minute and the workers start pulling. Every other setting has a default you can leave alone ([docs/configuration.md](docs/configuration.md)). To add it to an existing application step by step, with the questions to settle first, follow [Integrating](docs/integrating.md). ## What do I use for... ### Getting data sooner | I want | Use | | --- | --- | | An account's new data now, for a webhook or a "refresh" button | `monitor.SyncNowAsync(queue, owner, type)`: a burst of calls is one fetch | | One job to run before everything else | `NewJob.Priority = JobPriority.Urgent` | | A new account's history to load before the others | `Priority = JobPriority.High` on its `JobOwner`, in the owner source | | An account's waiting jobs moved forward once, by an operator | `monitor.PrioritizeOwnerAsync(queue, owner)` | | An account planned the moment it connects, not at the next round | `syncLane.PlanAsync(queue, owner)` | ### Stopping and repairing | I want | Use | | --- | --- | | A queue or an account stopped at once, for a while | `monitor.PauseAsync(queue, owner, reason, until: ...)`, then `ResumeAsync` | | No more jobs for an account that disconnected | `syncLane.CancelAsync(queue, owner, reason)`, and leave it out of the owner source | | Everything about an account gone for good | `syncLane.ForgetOwnerAsync(queue, owner)` | | One failed job tried again, from where it stopped | `monitor.RequeueJobAsync(id)`; every job with one error code: `RequeueByCodeAsync` | | A window fetched again from its first page | `monitor.RestartJobAsync(id)` | | One job never to run, so the jobs behind it go on | `monitor.SkipJobAsync(id, reason)` | | An API called more gently for a while | `monitor.LimitBudgetAsync(budget, key, limit, per, reason, until: ...)` | | An application's syncing stopped or started, without a deploy | `monitor.SetSwitchAsync(application, role, runWorkers, runPlanner, reason)`: kept in the database, read by every instance when it starts | | Web instances kept idle while a worker of the same build syncs | `SyncLane__Role=worker` in the worker's environment, and a switch per role ([switching](docs/operations.md#switching-an-application-on-and-off)) | | Several applications on one database, told apart | `SyncLane:Application`, a name of its own in each, and queue names that start with it | Every operator call is logged with who and why, and is also on HTTP with `SyncLane.AspNetCore` ([docs/monitoring.md](docs/monitoring.md)). ### Sending data out | I want | Use | | --- | --- | | Each delivery sent once, even if asked twice | `NewJob.DedupKey`, such as `$"movement:{id}"` | | One account's deliveries in order, a failed one holding the rest | `queue.Ordered = true` ([ordered queues](docs/operations.md#ordered-queues)) | | The handler and the monitor to know who asked | `NewJob.RequestedBy` | | The handler handed what it must send, instead of looking it up | `NewJob.Arguments`, read as `job.Arguments` | | The latest request for a key to win, whether the earlier one waits, failed or completed | `syncLane.EnqueueOrReplaceAsync(newJob)` | | A delivery that got through some other way closed without a run | `syncLane.CompleteAsync(queue, owner, type, keys)` | ## What it promises - **A page is handled at least once**, not exactly once. A crash between your write and the cursor save makes the page run again. Write with upserts. - **One job per lane at a time**, across every process that shares the table. - **A planned job is created once**, however many instances plan and however often. - **Nothing is lost on shutdown or crash.** The cursor on the row is where the job continues. ## Limitations - **PostgreSQL only, for now.** The lease is a single statement that relies on `FOR UPDATE SKIP LOCKED` and partial unique indexes. Support for other databases is planned; each will come with its own way of keeping the same guarantees, and its own tests. - **Periods are aligned to the clock.** "Every day" means once per UTC day. - **No dashboard.** The monitor is an API, and HTTP endpoints with `SyncLane.AspNetCore`; the screens are yours. ## Read on The same pages, as a website: [synclane-dev.github.io/synclane](https://synclane-dev.github.io/synclane/). | | | | --- | --- | | [Integrating](docs/integrating.md) | Adding SyncLane to an existing application from A to Z, written so you can hand it to an AI assistant | | [How it works](docs/how-it-works.md) | The table, a job's life, the statements and the indexes behind the guarantees | | [Planning](docs/planning.md) | History, slices, periods and overlap, and why | | [Recipes](docs/recipes.md) | Every part of a recipe; [with an AI assistant](docs/ai.md) | | [Working with jobs](docs/jobs.md) | Every call, results and errors, priorities, rate budgets in a handler | | [Watching it run](docs/monitoring.md) | The monitor, live changes, HTTP, metrics, health checks | | [Configuration](docs/configuration.md) | Every setting, and settings per environment | | [Operations](docs/operations.md) | Repairs, ordered queues, poolers, several instances and applications, the schema | | [Error codes](docs/errors.md) | Every code with its cause and fix | | [Production trial](docs/production-trial.md) | The checklist for a first run on something that may fail | | [The demo](docs/demo.md) | Four pretend shop accounts, with retries and a broken page, in Docker | ## Project status Version 0.12. Before 1.0 a minor version may still change the API; every change is listed in [CHANGELOG.md](CHANGELOG.md). The design comes from a job system that has synced external APIs for many accounts in production; this repository is a clean, general rewrite with its own tests, run on PostgreSQL 14 to 18 and through PgBouncer, but this code has not yet run in production itself. Try it on something that is allowed to fail first. ## Development ```bash dotnet build SYNCLANE_TEST_DB="Host=localhost;Username=postgres;Database=synclane_test" dotnet test ``` Without `SYNCLANE_TEST_DB` the PostgreSQL tests are skipped. Contributions are welcome; see [CONTRIBUTING.md](CONTRIBUTING.md). To report a vulnerability, see [SECURITY.md](SECURITY.md). ## Your responsibility SyncLane is a library. It runs inside your process, with the credentials you give it, against the database and the destinations you choose. It sends nothing to the SyncLane authors: there is no telemetry, no license check that calls home and no hosted service in between. Your data never passes through anyone but you. That also means the decisions are yours. When you use SyncLane, you are responsible for: - **Your right to call the API.** Having an account or app registration with the provider, accepting its terms, and staying within the limits and uses it allows. - **The pace you choose.** Concurrency, windows, retries and delays are settings. SyncLane applies them; it does not know what a provider tolerates. Start slow on an account that matters. - **Your credentials.** Where they are stored, who can read them and when they are rotated. Recipes ask your `ICredentialStore` for them page by page; SyncLane stores none. - **The data you pull and where you write it.** Including personal data and the laws that apply to it where you and your users are, such as the GDPR or Turkey's KVKK: what you keep, for how long and who may see it. - **What your handlers do.** SyncLane calls your code; it does not review it. Anything in this repository that describes a third-party API, including the demo and any example, is an illustration written by contributors. It is not a statement by the provider and may be out of date. Check the provider's own documentation before you rely on it. ## License [Apache License 2.0](LICENSE). The software is provided on an "AS IS" basis, without warranties or conditions of any kind, and no contributor is liable for damages arising from its use; sections 7 and 8 of the license state this in full. SyncLane is free to use, with no registration, account or paid edition, and it calls no host of its own: no telemetry, no license check, no update check. SyncLane is an independent open-source project. It is not affiliated with, endorsed by or supported by the PostgreSQL project or any API provider. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/jobs.md # Working with jobs from your code What the README's quick start leaves out: every call of `ISyncLane`, what a result means, how a handler says more than "it failed", who asked for a job, priorities, and rate budgets in a hand-written handler. ## Calls `ISyncLane` is the only service you inject. Every call returns a result instead of throwing for problems you can expect: | Call | Returns | What it is for | | --- | --- | --- | | `PlanAsync(queue, owner)` | `SyncResult` | Plan one owner now, for example right after an account connects. | | `EnqueueAsync(newJob)` | `SyncResult` | Put one job in by hand, outside the plan. The value is the new job's id. | | `EnqueueOrReplaceAsync(newJob)` | `SyncResult` | The same, but a job with the same owner, type and dedup key takes the new request's place instead of refusing it: the latest request for a key wins. `Replaced` says whether one was there. | | `CompleteAsync(queue, owner, type, keys)` | `SyncResult` | Close jobs by their dedup keys without running them, when the work was done some other way. The value is how many were closed. | | `GetJobAsync(id)` | `SyncResult` | One job with its arguments, which a list leaves out. | | `RequeueAsync(queue, owner?)` | `SyncResult` | Give failed, deferred and abandoned jobs fresh attempts. Cursors are kept. | | `CancelAsync(queue, owner, reason)` | `SyncResult` | Abandon what has not started, for example when an account disconnects. | | `GetJobsAsync(query)` | `SyncListResult` | One page of jobs by queue, owner, status or type, newest first, or of the owners whose name or key contains `Search` ("acme" finds every store of "Acme Toys"). Follow `NextCursor` for the next page; set `IncludeTotal` for a count. | | `GetProgressAsync(queue, owner)` | `SyncResult` | How far the first load of an owner is. Use it to show "connecting" without storing a status of your own. | | `MarkLoadedAsync(queue, ranges)` | `SyncResult` | Moving from another system: record the history it already loaded, so only what is older and what came after is fetched. | | `ForgetOwnerAsync(queue, owner)` | `SyncResult` | Delete everything about an owner that is gone for good. If it comes back, its history loads again. | ```csharp var result = await syncLane.EnqueueAsync(new NewJob { Queue = "shops", Owner = owner, Type = "orders", DedupKey = "resync-2026-10" }); if (!result.Succeeded) return result.Error!.Code == SyncErrorCodes.JobAlreadyExists ? Results.Ok("Already queued") : Results.Problem(result.Error.Message, statusCode: result.Error.Kind.ToHttpStatusCode()); return Results.Ok(result.Value); ``` ## Who asked `NewJob.RequestedBy` says who or what asked for a job, such as a user's id or `scheduler`: the handler reads it as `job.RequestedBy`, for example to send it along, and the monitor shows it. A sync-now records its caller there. It is the caller's data, never logged. ## Arguments `NewJob.Arguments` is what the handler needs for this one job and cannot look up, such as the body of a delivery as it was when the user sent it. It is text of your choosing, JSON for example, up to 262,144 characters; SyncLane stores it with the job and hands it back unread as `job.Arguments`. - SyncLane never writes it to a log, a trace, a metric or an error. The message of an exception your handler throws is stored in the job's `error` and logged as it is, so keep the arguments out of it: parse with `TryParse` instead of `Parse`, whose message quotes its input. - A list of jobs (`GetJobsAsync`, the monitor, the HTTP endpoints) leaves it out; `GetJobAsync(id)` returns it. - Put no credential in it: it is kept in the table. Keep it small, and let the handler read by the job's owner and dedup key whatever it can. ## The latest request wins A delivery that failed and is waiting for its next attempt is out of date as soon as the user sends a newer one. `EnqueueOrReplaceAsync` puts the new request in the old one's place: the same job, the same id and place in an ordered lane, with the new arguments, priority and requester and a fresh set of attempts; its window and lane stay as they were. A job that completed has no place left to keep: it is deleted, and a new job with a new id joins its lane at the back, as any new job would. A planned job is never replaced. A job that is running stays running. Its lease is revoked, so whatever its attempt reports is refused, and it runs again with the new arguments when that lease runs out, at most `LeaseDuration` later. Its lane stays closed until then. When the work got done some other way, for example a direct call that went through while the job was waiting, `CompleteAsync` closes the job by its key without running it. A running job is closed too and its lane is free at once; the attempt under way may still be inside your handler until its next page or heartbeat, and whatever it reports is refused. Nothing is counted as work done. ## Priority Jobs that are due run in this order: `Urgent` jobs, then the owners an operator moved forward with `PrioritizeOwnerAsync`, then `High`, `Normal` and `Low`. Within a level, types run in the order you declared them. A job takes its level from `NewJob.Priority`, or else from its owner: ```csharp // A stock change that must reach the marketplace before anything else in line. await syncLane.EnqueueAsync(new NewJob { Queue = "shops", Owner = owner, Type = "inventory", Priority = JobPriority.Urgent }); // A new customer whose history should load before the others: give it from your owner source. return accounts .Select(account => new JobOwner(account.Id, Name: account.Name) { Priority = account.IsNew ? JobPriority.High : JobPriority.Normal }) .ToList(); ``` An owner's priority applies to the jobs created after it changes; jobs already waiting keep theirs. Priority never cuts a running job: one account's jobs share a lane, so an urgent job of that account runs as soon as the job in its lane ends. `Job.PriorityLevel` and `Job.Prioritized` show where a job stands. ## Results and errors A failed result always means the call was understood and the answer is no: an undeclared queue, a duplicate job, a page size out of range. It never hides an outage; a database that cannot be reached still throws. Every error has a stable code such as `SL3101`, listed with its cause and fix in [docs/errors.md](errors.md). Call `ThrowIfFailed()` or `GetValueOrThrow()` when you would rather have an exception. Three exceptions let a handler say more than "it failed": - `JobThrottledException` when the other side asks you to slow down, optionally with the wait it named. - `JobAbandonedException` when a retry cannot help, for example when the account's access was revoked. - `JobPostponedException` when the job only has to wait: it gives its slot back without using an attempt and continues from its cursor later. A rate budget throws it for you when a token is far away, and so does a recipe with a budget when the API says "slow down". A hand-written handler does the same after `ThrottledAsync`: `throw new JobPostponedException(reason, pause)`. ## Rate budgets in a handler An API's limit belongs to an account, not to a job. Declare it once, and every job that calls the account draws from it: ```csharp builder.Services.AddSyncLane(lane => { lane.AddBudget("example-shop", limit: 2, per: TimeSpan.FromSeconds(1), burst: 40); lane.AddQueue("shops", queue => { /* ... */ }); }); ``` A recipe draws from it with `"rate": { "budget": "example-shop" }`. A hand-written handler calls `RateBudgets` before each request, and hands the permit back when the API answered `429`: ```csharp var permit = await budgets.WaitAsync("example-shop", job.Owner, cancellationToken); // ... send the request ... if (response.StatusCode == HttpStatusCode.TooManyRequests) await budgets.ThrottledAsync(permit, response.Headers.RetryAfter?.Delta, cancellationToken); ``` - **One bucket per budget and key**, usually the owner. Owners that share one set of credentials pass one key. - **Shared by every instance.** Buckets live in the `rate_buckets` table, so two instances together keep to the limit you declared, not twice it. Taking a token is one short statement, about 0.2 ms against a local database. - **A `429` pauses the whole bucket** for `Retry-After`, or one token's time, at least a second. Every job on the key, on every instance, waits; then the bucket goes on at 0.7 times its rate and climbs back while requests go through. The pause doubles, up to five minutes, only while the first request after each pause is refused again. Requests that were already on their way when the pause began do not count again. - **The limit is a ceiling, and the budget learns how much of it is safe.** A budget whose limit is right never sees a `429` and never changes. One whose limit is too high, or shared with another app, settles below it. For a limit nobody publishes, declare a generous ceiling and start lower: `AddBudget("example-shop", limit: 20, per: TimeSpan.FromSeconds(1), start: 0.25)`. Against simulated APIs with hidden limits it kept `429`s under 1% and reached 95 to 100% of the limit; it has not yet met a real one. - **A wait longer than `MaxBudgetWait`** (30 seconds) gives the job's slot back without using an attempt, so a paused budget never holds workers. - **What the API says counts too.** A recipe can name the headers in which the API says how many requests are left and when more come; the budget then stops at zero instead of running into a `429`, and notices another app spending the same quota. A hand-written handler passes the same numbers to `budgets.ReportRemainingAsync(permit, remaining, resetsIn)`. Those readings only ever lower the budget. See [docs/recipes.md](recipes.md#reading-what-the-api-says). - **A limit the API reports replaces the declared one**, up or down, on every instance: name its header in the recipe (`rate.headers.limit`), or call `budgets.ReportLimitAsync(permit, limit, per)` from a handler. When the API raises its limit, SyncLane follows without a deploy. - **An operator can lower a budget for a while**, without a deploy: `monitor.LimitBudgetAsync("example-shop", key: null, limit: 30, per: TimeSpan.FromMinutes(1), reason: "the API answers slowly", until: ...)`. It never raises one. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/configuration.md # Configuration Every setting has a default that is right for most installations; set one only for the case its description names. | Setting | Default | What it does | | --- | --- | --- | | `ConnectionString` | required | The database that holds the table. | | `ListenConnectionString` | `ConnectionString` | The same database, for the one connection per process that hears job changes. Set it when `ConnectionString` goes through a pooler in transaction mode. See [Behind a connection pooler](operations.md#behind-a-connection-pooler). | | `ListenForChanges` | `true` | Leave it as it is; to stop an application listening, for example to save connections, switch it off from the monitor (`SetListeningAsync`, [Switching an application on and off](operations.md#switching-an-application-on-and-off)). Turn it off here only where no connection can ever listen and nobody manages switches: workers then look for jobs every `PollInterval`, and nothing is opened or sent to hear changes. | | `Schema` | `synclane` | The schema of the `jobs` table. | | `CreateSchema` | `true` | Create the schema and apply missing migrations at start-up. Turn it off if you manage migrations: put `SyncLaneSchema.Script()` into one of yours, and SyncLane only checks at start-up that it has been applied. See [docs/operations.md](operations.md#running-the-schema-yourself). | | `RunPlanner`, `RunWorkers` | `true` | Leave them out, and switch instances on and off from the monitor: the decision then lives in one place, survives restarts and changes without a deploy ([Switching an application on and off](operations.md#switching-an-application-on-and-off)). Turn them off in settings only where nobody manages switches, for instances that should only enqueue and read; a switch still overrides them. | | `PlanInterval` | 1 minute | How often the planner looks for missing jobs. | | `PollInterval` | 5 seconds | How long an idle worker slot waits before it looks again. A job created or put back in line wakes it at once, from any instance. | | `AddBudget(name, limit, per, burst, start)` | none | A rate budget: at most `limit` requests per `per`, at most `burst` at once (default 1, evenly spaced). It starts at `start` times the limit (default 1) and learns below it. | | `Application` | the host's application name | The name instances register under, and the switches and the monitor know the application by. Copies of one application share its queues; another application that runs one of them is refused at start-up. Set it, to a name of its own, in every application that shares a schema with others: the default is the entry assembly's name, which projects built from one template often share (`Api`), and SyncLane warns when two applications use one. See [Several applications on one schema](operations.md#several-applications-on-one-schema). | | `Role` | none | What this copy of the application does, when one build runs as several kinds of process, such as web instances and a worker: set `SyncLane__Role=worker` in the worker's environment. The monitor shows it per instance, and switches are set per application and role. | | `KeepCompletedJobs` | 7 days | How long completed recurring and manual jobs stay before instances that run the planner delete them. Initial jobs and unfinished jobs stay. `null` keeps everything. | | `MaxBudgetWait` | 30 seconds | The longest a request waits for a budget's token inside a job; a longer wait postpones the job. | | `queue.Concurrency` | `1` | Jobs of the queue one process runs at once. `1` makes the queue strictly sequential. | | `queue.Ordered` | `false` | Take each lane's jobs strictly in the order they were created: one that failed or was abandoned holds the jobs behind it until it completes or is skipped. Only that queue and lane wait. See [Ordered queues](operations.md#ordered-queues). | | `queue.MaxAttempts` | `5` | Attempts in a row without saving a page before a job is deferred. | | `queue.LeaseDuration` | 5 minutes | How long a silent worker keeps its job. | | `queue.RetryBaseDelay`, `RetryMaxDelay` | 1 minute, 1 hour | Delay after a failure: base, doubled per attempt, capped. | | `queue.ThrottleBaseDelay`, `ThrottleMaxDelay` | 5 minutes, 30 minutes | The same for a `JobThrottledException` that names no wait. | ## Settings from configuration The code declares queues, job types, handlers and budgets. Their numbers can then come from configuration, per environment, without a deploy: ```csharp builder.Services.AddSyncLane(builder.Configuration.GetSection("SyncLane"), lane => { lane.ConnectionString = builder.Configuration.GetConnectionString("Postgres")!; lane.AddBudget("shop-api", limit: 2, per: TimeSpan.FromSeconds(1), burst: 40); lane.AddQueue("shops", queue => queue .Owners() .Windowed("orders", horizon: TimeSpan.FromDays(730), slice: TimeSpan.FromDays(30), every: TimeSpan.FromMinutes(15))); }); ``` ```json "SyncLane": { "Application": "shop", "Queues": { "shops": { "Concurrency": 4, "Types": { "orders": { "Every": "00:05:00", "Slice": "7.00:00:00" } } } }, "Budgets": { "shop-api": { "Limit": 4 } } } ``` - Everything in the table above can be set: top-level settings by name, `Queues:` for a queue, `Queues::Types:` for `Horizon`, `Slice`, `Every`, `Overlap` and `Offset`, and `Budgets:` for `Limit`, `Per`, `Burst` and `Start`. - Configuration overrides what the code declares and never adds to it. A queue, type, budget or setting the code does not know stops the start with `SL1012`, naming its path, so a typo never passes silently. Every problem is reported at once. - Names ignore case, as configuration keys do, so an environment variable such as `SYNCLANE__QUEUES__SHOPS__CONCURRENCY=4` works. - Time spans are written `hh:mm:ss` or `d.hh:mm:ss`. A value that cannot be read stops the start with `SL1013`, which names the path but never the value. - The values are checked like values from code. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/how-it-works.md # 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.

```mermaid flowchart LR owners["Your accounts
(IOwnerSource)"] --> planner["Planner
what should exist
minus what exists"] planner -->|"insert, on conflict do nothing"| table[("synclane.jobs")] table -->|"take the next job
whose lane is free"| worker["Worker slot"] worker --> handler["Your handler
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. ```mermaid 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: - `UNIQUE (queue, owner, type, dedup_key)` makes planning repeatable. Several instances can plan at the same moment and every job is created once. - `UNIQUE (queue, lane) WHERE status = 'running'` makes a lane exclusive. Two workers can pick different jobs of one lane in the same instant; the database lets one through and the other asks again. 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](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](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: ```sql 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: - **Who is a candidate.** A job that is due and is `pending`, `failed`, `running` with a lease that ran out, or `deferred` while nothing else is waiting in its lane. - **The lane rule.** A candidate is skipped while another job of its lane is `running`. Note that this does not ask whether that other job's lease is still alive. A lane with a dead worker stays closed until that same job is taken over; only then does the lane move on. This is deliberate, see [The lane is closed by the row, not by the lease](#the-lane-is-closed-by-the-row-not-by-the-lease). - **The order.** Deferred jobs last. Then by type, in the order the types were declared. Then the newest window first, so a fresh recurring window runs before older slices of history. Then by due time. - **How it is found.** The index `jobs_lease_order` holds the jobs that have not completed in exactly this order, so PostgreSQL walks it from the front and stops at the first job that passes the checks above, instead of reading and sorting every waiting job. On 25,000 waiting jobs that is 0.1 ms instead of 20 ms; under load it was the difference between the lease being the bottleneck and not. - **`SKIP LOCKED`.** Two slots asking at once do not wait for each other; each gets a different row. ### 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: ```sql 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: ```mermaid 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
(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
(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`](recipes.md) 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 - **Write idempotently.** A page can run twice: after a crash between your write and the cursor save, and in the overlap between two windows. Upsert by the other side's identifier. - **Return a cursor you can resume from.** If the other side's page tokens expire, keep a slice small enough to finish well inside their lifetime. A slice is the largest unit of work that cannot be split. - **Respect the cancellation token.** That is how a stopping worker gets its job back to the table quickly. - **Say what kind of failure it was** when you know: `JobThrottledException` for "slow down", `JobAbandonedException` for "this will never work", `JobPostponedException` for "not a failure, only wait". --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/planning.md # Planning Planning decides which jobs exist. It is the part of a sync system that looks easiest and goes wrong most quietly, so it has one rule and this page explains where the rule comes from. ## The rule > Planning compares the jobs that should exist with the jobs that exist, and adds only what is missing. It can be called at any time, any number of times. Nothing in the planner remembers that it ran. There is no "already planned" flag, no early exit, no last-run timestamp. The tables are the only memory: the jobs, and `coverage`, a summary of what has been planned per owner and type. The statement that inserts jobs also writes the summary, so the two never disagree, and the planner reads one row per owner and type instead of every job ever created. Old jobs can then be deleted without changing what is planned. ## Two questions, two owners Most planning bugs come from mixing these up: | Question | Who answers it | What happens | | --- | --- | --- | | A job that should exist has **no row** | The planner | The row is inserted. | | A row exists but the job **stopped** (failed, deferred, abandoned) | Retry and requeue | The row goes back to `pending`. | This is why **coverage does not look at status**. A slice of history that was abandoned is still "planned". Bringing it back is the job of a requeue, which keeps its cursor. If the planner counted only healthy rows, it would insert a second row for the same slice while the first one is waiting for its retry, and the two would then fetch the same range. **One exception: a recurring job that was abandoned is replaced by the next one.** When the next period comes, the planner deletes the abandoned recurring jobs of that owner and type in the same statement that inserts the new one, and the new window starts where the oldest of them started. An account whose credentials were revoked would otherwise add an abandoned row every period, and the windows they missed would stay missed after the credentials are fixed. The newest job always carries the current error. A requeue that comes first still wins: only rows that are still abandoned are deleted. ## What should exist You declare each job type as one of two kinds. **Snapshot**: a type that reads everything on each run, like a product list. - One `initial` job per owner. - If `every` is set: one `recurring` job per period, as long as no job of the type is still outstanding for that owner. **Windowed**: a type that reads a range of time, like orders. - `initial` jobs that cover the range from the horizon to today in slices, newest first. - If `every` is set: one `recurring` job per period whose window starts where coverage ends (minus `overlap`) and ends at the time of planning. ``` today = midnight UTC of the current day covered = the oldest window_start among the owner's initial jobs, or today if there are none horizon = today - Horizon for each slice from covered back to horizon: # stops exactly at the horizon insert initial job (slice.start, slice.end) if no recurring job of this type is outstanding and none was created in the current period: from = the newest window_end among all the owner's jobs of this type start = from - Overlap, or the oldest start of abandoned recurring jobs if that is earlier insert recurring job (start, now), deleting those abandoned recurring jobs ``` `covered`, `from` and the creation times come from the summary; whether a job is outstanding or abandoned comes from the open rows, which clean-up never deletes. The inserts go through `INSERT ... ON CONFLICT DO NOTHING` on the unique index `(queue, owner, type, dedup_key)`. The key is `initial` for a snapshot, `initial:` for a slice of history and `recurring:` for a recurring job. So even if two instances compute the same plan at the same moment, each job is created once. ## What that gives you These are the numbers from `PlanningTests`, which runs the planner against PostgreSQL with a clock it controls: | Situation | Jobs created | | --- | --- | | New owner, 60 days of history in 30-day slices | 2 | | Planned again the same day | 0 | | Planned again five hours later | 0 | | Horizon raised from 60 to 730 days | 23, only the gap | | Planned again after raising | 0 | | Planned the next day | 0 | | In total | 25 slices, 730 days, no hole and no overlap | And for what is new: - After an outage of any length, the next recurring job has **one** window that covers everything since coverage ended. Nothing has to be "caught up" by hand. - While a recurring job is still pending or running, no second one is stacked behind it. The window of the next one simply starts where this one ends. - A new job type added to a queue is planned for every owner that is already connected, on the next round. ## Three mistakes this design exists to prevent All three were made in the system this design comes from. Each one looked reasonable when it was written. ### 1. The "already planned" latch ```csharp if (await jobs.AnyAsync(job => job.Owner == owner && job.Mode == Initial)) return; ``` One initial row blocked all further planning for that owner, forever. It was harmless until the history horizon was raised from 60 days to two years: new accounts got two years, and every account that was already connected silently stayed at 60 days. Nothing failed. Reports that needed last year's numbers were simply empty for the older accounts. The planner has no early exit now. If you find yourself adding one, the generator underneath is probably not repeatable, which is the next mistake. ### 2. Slices anchored to the time of the call ```csharp foreach (var slice in Slices(end: DateTime.UtcNow, days: 60)) ``` Slices that start from "now" are different every time: called an hour later, every `window_start` has moved by an hour. Duplicates are recognised by `window_start`, so planning twice produced a second, overlapping set of slices. The latch above was there to hide exactly this. The two were locked together: the latch existed because the generator was not repeatable. The order of the fix matters. **First anchor the slices to a fixed point, then remove the latch.** In SyncLane slices are anchored to midnight UTC, and the generator takes an explicit end point: it continues from the edge of what is covered and stops exactly at the horizon. ### 3. Deduplicating recurring jobs by their window A recurring job also carries a window, so it is tempting to recognise a duplicate the same way as for history: same type, same `window_start`. In that system the start of the recurring window was derived from the data: the latest "updated at" already stored, minus a few minutes of lag. Now consider a day on which a job brings nothing new. The latest "updated at" does not move. The next day the same window start is computed, it is found to be a duplicate, and nothing is planned. From that day on the account never gets a recurring job again, because the only thing that could move the data forward is the job that is no longer being planned. The lag made it worse: the last run had re-read a few boundary records, so its processed count was not zero and the account looked alive. Six accounts stopped this way, one after the other, over several weeks, before anyone connected the dots. So the two modes are deduplicated by different things, on purpose: - `initial`: by window start. The set of slices is fixed and must not be planned twice. - `recurring`: by period. "Has this owner had its job for this period?" has nothing to do with which range the job covers. And the window of a recurring job is derived from the jobs table (where coverage ends), not from the data, so it moves forward even when a run finds nothing. ## Before you change something - **A new job type**: declare it. Owners that are already connected get it on the next round. - **A longer horizon**: change the number. The gap is filled, existing slices are untouched. - **A different slice length**: existing slices stay as they are; only ranges that are not covered yet are cut with the new length. - **Do not add an early return to the planner.** It is the one thing that breaks repeatability. - **Do not filter coverage by status.** It collides with retry and requeue. - **Do not deduplicate recurring jobs by window.** It can lock an owner out for good. - **Moving from another system**: call `MarkLoadedAsync` with the ranges it already loaded, before the planner runs for those owners. Only what is older and what came after is fetched. See [operations.md](operations.md#moving-from-another-system). - **An owner that is gone for good**: call `ForgetOwnerAsync`. Deleting its rows by hand leaves the summary behind, and if the owner came back its history would never be loaded again. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/operations.md # Operations SyncLane has no admin tool because the table is one. This page collects the statements that answer the usual questions, and the settings that are easy to get wrong. All examples use the default schema, `synclane`. ## Looking `ISyncLaneMonitor` answers the usual questions without SQL: the state of each queue, whose data is old and why, each owner's jobs counted by status, failures grouped by error code, rate budgets, instances, and volume per hour or day. See [Watching it run](monitoring.md). The queries below are for everything else. **Finding an owner by name.** Give `JobOwner` a name in your owner source, for example the customer and its store, and `GetJobsAsync`, `GetFreshnessAsync`, `GetFreshnessOwnersAsync` and `GetJobOwnersAsync` find owners by any part of it with `Search`, ignoring case. The key and the name live in `synclane.owners`, one row per queue and owner; a search reads that small table and never the jobs. How many jobs each owner found by name has given up on is `GetJobOwnersAsync` with `Search` and `Status = JobStatus.Abandoned` (`GET /synclane/jobs/owners?queues=shop.orders&queues=shop.stock&search=acme&status=abandoned`), counted across the queues you name. The same count in SQL, per queue: ```sql SELECT o.queue, o.owner, o.name, count(*) FILTER (WHERE j.status = 'abandoned') AS given_up FROM synclane.owners AS o JOIN synclane.jobs AS j ON j.queue = o.queue AND j.owner = o.owner WHERE o.name ILIKE '%acme%' GROUP BY o.queue, o.owner, o.name; ``` What is running right now, and who has it: ```sql SELECT id, owner, lane, type, cursor, processed_count, leased_by, heartbeat_at FROM synclane.jobs WHERE status = 'running' ORDER BY started_at; ``` What is in trouble: ```sql SELECT id, owner, type, status, attempt_count, next_run_at, error FROM synclane.jobs WHERE status IN ('failed', 'deferred', 'abandoned') ORDER BY updated_at DESC; ``` How far each owner's first load is: ```sql SELECT owner, count(*) AS jobs, count(*) FILTER (WHERE status = 'completed') AS done, count(*) FILTER (WHERE status = 'abandoned') AS given_up FROM synclane.jobs WHERE mode = 'initial' GROUP BY owner ORDER BY owner; ``` Which range of an owner's orders is covered, and where the holes are: ```sql SELECT window_start, window_end, mode, status, processed_count FROM synclane.jobs WHERE owner = 'globex' AND type = 'orders' AND window_start IS NOT NULL ORDER BY window_start; ``` Why a lane is not moving. One of these rows is the answer: a job that is running, or one that is waiting for `next_run_at`: ```sql SELECT id, type, status, attempt_count, next_run_at, lease_expires_at, leased_by, error FROM synclane.jobs WHERE lane = 'globex' AND status IN ('pending', 'running', 'failed', 'deferred') ORDER BY priority, window_start DESC NULLS LAST; ``` Which rate budgets are paused, and until when. `generation` counts the pauses of a bucket; `last_pause` is the most recent one's length: ```sql SELECT budget, key, refilled_at AS paused_until, generation, throttled_at, last_pause FROM synclane.rate_buckets WHERE refilled_at > now() ORDER BY refilled_at DESC; ``` What each bucket has learned. `rate` is the current rate in requests a second, never above the ceiling; `rate_max` is the rate that last caused a `429`; `reported_rate` is the limit the API last reported, which is the ceiling in place of the declared limit when it is there. A rate far below the ceiling means the API, or another app on the account, allows less than it says: ```sql SELECT budget, key, round(rate::numeric, 3) AS rate, round(rate_max::numeric, 3) AS rate_max, round(reported_rate::numeric, 3) AS reported_rate, throttled_at FROM synclane.rate_buckets ORDER BY budget, rate; ``` ## Changing `ISyncLaneMonitor` has an emergency stop and the usual repairs, for any queue in the schema: | Call | What it does | | --- | --- | | `PauseAsync(queue, owner?, reason, by, until?)` | Stops a queue, or one owner on it, at once. Running jobs of it are cut on every instance and handed back without using an attempt; nothing of it is taken until `ResumeAsync` or `until`. Planning goes on, and the next window reaches back over the pause, so nothing is lost. The page that was cut runs again on resume, which is why handlers write idempotently. | | `ResumeAsync(queue, owner?, by)` | Lifts it. Idle workers wake at once. | | `LimitBudgetAsync(budget, key?, limit, per, reason, by, until?)` | Lowers a rate budget, or one key of it, for a while: "the API answers slowly, halve our rate for an hour". Every instance obeys from its next request. It only ever lowers: the declared limit, or the one the API reports, stays the upper bound. When it ends, the rate climbs back as it learns. Permanent changes belong in the budget's declaration. | | `ClearBudgetLimitAsync(budget, key?, by)` | Lifts it. | | `RequeueJobAsync(id)` | Gives one failed, deferred or abandoned job fresh attempts, keeping its cursor. | | `SkipJobAsync(id, reason)` | Takes one job that is not running out of line for good, without running it, so the jobs behind it in an ordered lane go on. The job is deleted; the actions log keeps who skipped which job and why. Its dedup key is free again. | | `RestartJobAsync(id)` | Runs one job again from its first page, a completed one too, for a window whose data has to be fetched again. | | `RequeueByCodeAsync(queue, code)` | Requeues every failing, deferred and abandoned job of the queue with that error code, after you fixed the cause. | | `SyncNowAsync(queue, owner, type)` | Fetches the owner's new data now, from where its completed data reaches, at high priority. While that job waits, later calls stretch it to now instead of adding jobs, so a webhook storm is one fetch. A type without windows is fetched whole. The planner's own jobs are not touched. | | `PrioritizeOwnerAsync(queue, owner)` | Moves the owner's waiting jobs ahead of every other owner's, urgent jobs excepted, keeping its own order of levels and types. Jobs created later get the owner's usual priority; to keep it ahead, give it a `JobOwner.Priority`. | Apart from the pause, none of them touches a running job. A call about one job that cannot act says why (`SL3008`, `SL3102`); the others return how many jobs they changed. Every one of them is written to the `actions` table with who asked (`by`, which the HTTP endpoints fill in from the signed-in user), why, and how many jobs it changed. `GetActionsAsync` lists them, newest first, for 400 days. `GetPausesAsync` lists the pauses in force; `GetOverviewAsync` and `GetFreshnessAsync` show them too. `GetBudgetLimitsAsync` lists the budget limits in force, and `GetBudgetsAsync` shows on each key the limit it obeys. An instance of a version before pauses keeps taking jobs of a paused queue, and paces at the declared limit whatever an operator or the API sets. Upgrade every instance before relying on either. Everything SyncLane does is a plain update, so you can do the same from `psql` when you need something it does not offer. Give stopped jobs of one owner fresh attempts (this is `RequeueAsync`). The cursor is left alone on purpose: ```sql UPDATE synclane.jobs SET status = 'pending', attempt_count = 0, next_run_at = now(), error = NULL, completed_at = NULL, updated_at = now() WHERE owner = 'globex' AND status IN ('failed', 'deferred', 'abandoned'); ``` Start one job over from its first page. Only do this if the other side's cursor is no longer valid: ```sql UPDATE synclane.jobs SET cursor = NULL, processed_count = 0 WHERE id = 33 AND status <> 'running'; ``` Hold an owner back for an hour without losing anything: ```sql UPDATE synclane.jobs SET next_run_at = now() + interval '1 hour' WHERE owner = 'globex' AND status IN ('pending', 'failed'); ``` Let one job jump the queue, as if it had been enqueued urgent: ```sql UPDATE synclane.jobs SET priority = priority - 10000000 WHERE id = 33; ``` Do not set a row to `running` by hand, and do not change `leased_by`. Those two columns are how a worker proves a job is still its own. ## Keeping the table small SyncLane deletes old jobs itself. Instances that run the planner do it at start-up and then every hour, in batches of 1,000, for their own queues only: | Kept | Deleted | | --- | --- | | Initial jobs. They are bounded by the horizon, `GetProgressAsync` counts them, and they record what history was loaded. | Completed recurring and manual jobs older than `KeepCompletedJobs` (default 7 days). | | Jobs that have not completed: pending, running, failed, deferred and abandoned. | | Set `KeepCompletedJobs = null` to keep every job. Deleting is safe at any age: the planner reads `coverage`, not the history. An abandoned recurring job does not pile up: the next period's job replaces it and reaches back over its window. An abandoned slice of history waits for `RequeueAsync`. `rate_buckets` holds one small row per budget and key, updated in place. Rows of keys you no longer use can be deleted; a key that is used again starts with a full bucket. When an account only disconnects, call `CancelAsync` and stop returning it from your `IOwnerSource`. If it connects again, call `RequeueAsync` for it: its abandoned slices are still planned and come back with their cursors. When an account is removed for good, stop returning it from your `IOwnerSource`, then call `ForgetOwnerAsync`, then delete its data. A job running at that moment stops at its next page, and that page may still reach your handler. Do not delete its rows by hand: the summary would stay, and if the account came back its history would never be loaded again. ## Moving from another system If another system already loaded an account's history, record it with `MarkLoadedAsync` before the planner runs for that account. Each range becomes a completed initial job. The planner then fetches only what is older, back to the horizon, and what came after, with the next recurring window. ```csharp var ranges = oldJobs .GroupBy(job => (job.StoreId, job.Type)) .Select(group => new LoadedRange { Owner = new JobOwner(group.Key.StoreId.ToString()), Type = group.Key.Type, Start = group.Min(job => job.WindowStart), End = group.Max(job => job.WindowEnd) }) .ToList(); var result = await syncLane.MarkLoadedAsync("orders", ranges); result.ThrowIfFailed(); ``` Mark only ranges without holes: a hole inside a marked range is never fetched. If the old system's history has gaps, mark each unbroken run as its own range. - It is safe to run twice: the same range is recorded once. - One bad range marks nothing, and every problem is returned at once (`SL3006`, `SL3007`). - Only windowed types can be marked. A snapshot type reads everything on each run anyway. - A range must end by now. For a type without `every` it must reach today (UTC), because such a type never loads what came after its history. A safe order: 1. Deploy with `RunPlanner` and `RunWorkers` off. 2. Mark the history. 3. Stop the old system. 4. Turn SyncLane on. ## Choosing the numbers **`slice`** is the setting with the most consequences. One slice is one job, and a job is the largest unit of work that cannot be split. Work out how long one slice takes for your biggest account at the other side's rate limit. The system this design comes from once tripled its slice from 30 to 90 days to "have fewer jobs". For the largest account a single slice then held about 43,000 records, 430 pages, roughly twenty hours of requests, against page tokens that lived for twenty-four. Every hiccup late in a slice cost most of a day. Small slices finish, and a finished slice is progress that cannot be lost. **`LeaseDuration`** only needs to cover the time it takes to notice a dead process, because the heartbeat renews it during long pages. The default of five minutes means a job whose worker died waits at most five minutes to be taken over. Going much lower mostly buys false alarms during garbage collection pauses or a slow database. **`Concurrency`** is per process and per queue. Three instances with `Concurrency = 4` run up to twelve jobs of that queue at once, and still at most one per lane. Set it to `1` for an API that must be called strictly one request at a time, whatever the account. More instances or more slots make more accounts load side by side. They do not make one account load faster: its jobs share a lane, and its requests share the API's limit for that account. A new account's history is loaded newest slice first, so its recent data arrives first; `PrioritizeOwnerAsync` moves it ahead of the others in line. **Per environment.** Every number here can come from configuration instead of code, with `AddSyncLane(configuration, ...)`: see [Settings from configuration](configuration.md#settings-from-configuration). Raise `Concurrency` or widen `every` in one environment without a deploy. **`MaxAttempts`** counts pick-ups since the job last saved a page, so it limits failures in a row, not over a job's life. A throttle counts only when the recipe or handler has no rate budget; with one, the budget's pause is what protects the API, and the job is postponed instead. With the defaults a job that keeps failing on one page is deferred after about fifteen minutes of ordinary failures, or more than an hour of unbudgeted throttling. A job whose budget keeps being refused waits as long as the budget's pause, which grows to five minutes, and is never deferred for it: it shows as `pending` with an `SL5105` error, and `synclane.budget.paused` grows. That is the signal to look at the account. **`every` and `overlap`**: a recurring window starts `overlap` before the previous one ended. Use the overlap to cover records that show up late on the other side, and rely on upserts to make the double read harmless. ## Metrics and traces All metrics belong to the meter `SyncLane` (`SyncLaneTelemetry.MeterName`). Every one carries `synclane.queue` and, except the planner metrics, `synclane.job.type`. Owners and lanes are never tags: there can be thousands of them and they often identify customers. Use the table for questions about one owner. | Metric | Unit | What it counts | | --- | --- | --- | | `synclane.job.taken` | `{job}` | Jobs a worker took. | | `synclane.job.wait` | `s` | Time between a job becoming due and a worker taking it. Rising wait with idle CPU means too few worker slots, or lanes that are always busy. | | `synclane.job.finished` | `{job}` | Runs that ended, with `synclane.job.outcome`: `completed`, `failed`, `deferred`, `abandoned`, `released` (worker stopping), `postponed` (waiting, attempt not counted), `paused` (cut by a pause, attempt not counted) or `lease_lost`. | | `synclane.job.duration` | `s` | Time from taking a job to the end of the run, with the same outcome tag. | | `synclane.page.completed` | `{page}` | Pages a handler returned. | | `synclane.page.duration` | `s` | Time a handler took for a page it returned. | | `synclane.record.processed` | `{record}` | Records the handlers reported. | | `synclane.job.throttled` | `{job}` | Runs that ended with a `JobThrottledException`: throttles without a rate budget, which use an attempt. They are also counted as `failed`, `deferred` or `abandoned`. With a budget, a throttle postpones the job and shows in `synclane.budget.paused`. | | `synclane.planner.planned` | `{job}` | Jobs the planner added. | | `synclane.planner.failed` | `{run}` | Planner runs that failed. | | `synclane.budget.wait` | `s` | Time a request waited for a token of a rate budget. Tagged `synclane.budget` only; the key is an owner and never a tag. | | `synclane.budget.paused` | `{pause}` | Times a rate budget was paused because the API answered `429`. Tagged `synclane.budget` only. | | `synclane.budget.exhausted` | `{pause}` | Times a rate budget waited for a reset because the API's headers said nothing was left. Tagged `synclane.budget` only. Expected when a quota is used to the full. | Traces come from the activity source `SyncLane` (`SyncLaneTelemetry.ActivitySourceName`). A `synclane.job` span covers one run of a job and carries `synclane.job.id`, `synclane.job.mode`, `synclane.job.attempt` and, at the end, `synclane.job.outcome`; a failed run records the exception and sets the span status to error. Each page is a `synclane.page` span inside it with `synclane.page.processed`. The cursor is not recorded, because some APIs put tokens in it. Four signals worth an alert: - `synclane.job.finished{outcome="abandoned"}` above zero. Something waits for a person. - `synclane.job.throttled` growing faster than `synclane.job.taken`. The pace is too high for the other side: give the recipe or handler a rate budget. - `synclane.job.finished{outcome="lease_lost"}` above zero. A worker stalled longer than `LeaseDuration`, or clocks disagree. - `synclane.budget.paused` growing steadily. The declared budget is above what the API allows now: lower it. Another app on the same account can cause this too. `synclane.budget.exhausted` growing is not a problem: it means SyncLane stopped at zero instead of being throttled. ## Ordered queues Some deliveries must arrive in the order they were made: a stock movement, then the next one for the same company. Declare their queue ordered: ```csharp options.AddQueue("movements", queue => { queue.Ordered = true; queue.Handle("movement"); }); ``` - A job waits while an older job of its lane is unfinished: pending, running, failed, deferred or abandoned. When movement 1 is abandoned, movement 2 and the rest of that lane wait. - Only that queue and that lane wait. Other lanes go on, and so does every other queue, pulls included. - Fix the cause and requeue the job (`RequeueJobAsync`); when it completes, the lane goes on. A job that must not be sent at all is skipped (`SkipJobAsync(id, reason)`): it is deleted, the actions log keeps who skipped it and why, and the lane goes on. - A delivery that reached the other side some other way is closed by its key (`CompleteAsync`), and a newer request for the same key takes the held job's place (`EnqueueOrReplaceAsync`); either way the lane goes on. - A deferred job is tried again when due instead of stepping aside, since the jobs behind it are waiting for it. - Priority still orders the heads of different lanes; within a lane, order of creation wins over priority. - The lease finds the head of each lane through the index `jobs_lane_order`: on 100,000 waiting jobs in 1,000 lanes, about 6 ms. ## Health checks Register `SyncLaneHealthCheck` with your health checks and point your orchestrator's probe at the endpoint: ```csharp builder.Services.AddHealthChecks().AddCheck("synclane", tags: ["ready"]); app.MapHealthChecks("/health/ready", new() { Predicate = check => check.Tags.Contains("ready") }); ``` | Status | When | What to do | | --- | --- | --- | | Unhealthy | The database cannot be reached | Check PostgreSQL and `ConnectionString`. The description names the error's type only. | | Unhealthy | The schema lacks migrations | Apply `SyncLaneSchema.Script()`, or set `CreateSchema` to true. | | Unhealthy | No heartbeat for two minutes | Other instances count this one as gone, and another application may take its queues. The log says why the heartbeat fails. | | Degraded | Starting | Nothing: it has not registered yet. | | Degraded | The latest planning round of a queue failed | No new jobs are planned for it until a round succeeds. The log says why, usually the owner source. | | Degraded | A switch turns workers or the planner on, but another application runs one of the queues | They stay off. Rename the queue in one of them, or give both the same `Application`. See [Switching an application on and off](#switching-an-application-on-and-off). | | Degraded | Another application registers under the same name | Give one of them a name of its own with `options.Application`. See [Several applications on one schema](#several-applications-on-one-schema). | | Degraded | It does not hear job changes | Workers poll every `PollInterval`. See [Behind a connection pooler](#behind-a-connection-pooler). | ASP.NET Core answers 200 for degraded and 503 for unhealthy by default, so a readiness probe keeps a degraded instance in service. Use it for readiness rather than liveness: a database outage makes every instance unhealthy at once, and restarting them all helps nothing. ## Several instances Run as many instances as you like against the same table. Planning is safe to do from all of them, and so is taking jobs. If your web instances should not do background work, give the worker a role and switch the web instances off from the monitor ([Switching an application on and off](#switching-an-application-on-and-off)). `ISyncLane` works the same either way. ## Switching an application on and off **What a process is comes from its settings; whether it works comes from the database.** The settings name the process, and nothing else about this: | What | Where | Example | | --- | --- | --- | | The application's name, its own on the schema | `SyncLane:Application` in `appsettings.json`, committed | `"Application": "shop"` | | The role, only when one build runs as web and worker | the worker's environment | `SyncLane__Role=worker` | | Whether it runs workers and the planner | a switch per application and role, in the database | set from the monitor, below | `RunWorkers` and `RunPlanner` stay at their default, `true`, and a switch set from the monitor overrides them, without a deploy, a configuration change or a visit to the server. With ten applications on one schema, that is one place to start and stop all of them: ```csharp await monitor.SetSwitchAsync("shop", role: "worker", runWorkers: true, runPlanner: true, reason: "launch", by: user); ``` Over HTTP: `POST /synclane/switch?application=shop&role=worker&workers=true&planner=true&reason=launch`, and `GET /synclane/switches` lists every application and role with its switch and what its live instances run. - **Per application and role.** One build often runs as web instances and a worker under one application name. Give the worker a role in its environment (`SyncLane__Role=worker`) and switch that role; the web instances, with no role, are left as they are. - **A value overrides, `null` gives the choice back.** `runWorkers: false` stops the workers whatever the settings say; `runWorkers: null` returns to `RunWorkers`. - **Off is immediate, on takes up to half a minute.** Instances whose workers run hear the switch at once, and their running jobs are handed back with their cursors, without using an attempt, as at shutdown. Instances that run nothing read it with their next heartbeat; they open no listening connection for it. - **A switch survives restarts, deploys and new replicas.** It belongs to the application and role, never to an instance, whose id changes with every start. Each instance reads it when it registers, before its planner and workers start, so a container that crashes and comes back, or a replica added by the orchestrator, does what the switch says from its first moment. - **An application can be switched before it starts.** Set the web instances off and the worker role on, then deploy: neither works where it should not, even for a moment. - **Switches are per database.** Set them once in each environment (test, staging, production). Where none is set, every instance runs workers and the planner, as without switches. - **On is checked like a start.** If another application runs one of the queues, the instance stays off, logs a warning and its health check says why (`SL1011`). - **Listening has a switch of its own.** Each instance keeps one connection open to hear job changes, which wakes idle workers at once and feeds live views. `SetListeningAsync("shop", role: null, listen: false, reason: "save connections", by: user)`, or `POST /synclane/switch/listen?application=shop&listen=false&reason=…`, closes it on the application's instances at once: their workers look for jobs every `PollInterval` instead, and live views of them stay quiet. The workers and the planner keep what their switch says. `listen: null` gives the choice back to `ListenForChanges`; switched on again, an instance opens the connection within half a minute. `GetSwitchesAsync` counts the live instances that listen (`Listening`). With many applications on one database, this is how to keep the count of connections down without a deploy. Switch it on only where a connection can listen: behind a pooler in transaction mode, only for an application that sets `ListenConnectionString` around it ([Behind a connection pooler](#behind-a-connection-pooler)). - **Every change is in the actions log** with who and why. `GetOverviewAsync` shows per queue how many live instances plan it and run its workers: zero planners means no new jobs. - Instances of versions before 0.7 do not read switches and run as their own settings say. `GetSwitchesAsync` counts them per application and role (`IgnoringSwitch`, under the empty role, since they have none) and `GetInstancesAsync` marks each (`FollowsSwitches` false). Switch an application once that count is zero. Rate budgets are shared through `rate_buckets`: every instance takes its tokens from the same row, and a `429` heard by one instance pauses the key on all of them. Declare the same budgets on every instance that runs workers. Taking a token is one statement that locks the bucket's row for a moment; measured against a local PostgreSQL 18, one key served about 12,000 tokens a second to eight callers, far more than any API we know allows. Keep the clocks of your instances in sync. Leases, due times and token refills are computed with the clock of the instance that asks. For leases a skew of seconds does not matter; for a budget, an instance whose clock runs one second ahead can let one second's worth of extra tokens through. ## Behind a connection pooler Everything SyncLane writes and reads works through a pooler in transaction mode, such as PgBouncer with `pool_mode = transaction`: every statement stands alone or runs in its own transaction, nothing is kept in the session, and its one advisory lock ends with its transaction. CI runs the whole test suite through PgBouncer in that mode. The exception is the one connection each process keeps open to hear job changes, which wake idle workers at once and feed `WatchAsync` and the `/stream` endpoint. It uses `LISTEN`, and a pooler in transaction mode accepts `LISTEN` without an error and never delivers what it hears, because the server connection that listened goes back to the pool. Worse, that server connection stays registered: every change sent to the channel afterwards reaches whichever client the pooler lends it to next, and those clients, any application's, time out now and again. So SyncLane checks before it listens. Each time that connection opens, it listens on a channel of its own that nothing else uses, sends a probe there through `ConnectionString`, and waits five seconds to hear it. Only then does it listen on the schema's channel. If it hears nothing, it logs a warning that names `ListenConnectionString`, closes the connection and does not listen again until the next start. Workers then look for jobs every `PollInterval`, and live views stay quiet. At most the probe's own channel stays registered behind the pooler, and nothing ever sends to it. To keep live changes, give the listening connection a way around the pooler: ```json { "SyncLane": { "ConnectionString": "Host=pgbouncer;Port=6432;Database=app;Username=app", "ListenConnectionString": "Host=db;Port=5432;Database=app;Username=app" } } ``` It costs one server connection per process. A pooler in session mode works too, and so does a proxy that pins a session to one server connection when it sees `LISTEN`. Without a pooler, leave `ListenConnectionString` out. Where nothing can get around the pooler, switch listening off from the monitor before the application first starts: `SetListeningAsync(application, role, listen: false, reason)`, or `POST /synclane/switch/listen?application=…&listen=false&reason=…` ([Switching an application on and off](#switching-an-application-on-and-off)). Each instance reads the switch before it listens, so no connection is opened and no probe is sent; `ListenForChanges = false` in configuration does the same where nobody manages switches. workers look for jobs every `PollInterval`, which you may want shorter, and the health check does not count it as a problem. Do this rather than leaving the warning: the probe itself is one notification, sent at each start, and behind PgBouncer in transaction mode it can reach whichever client the pooler lends that server connection to just then. Versions before 0.4.1 listened on the schema's channel through the pooler. PgBouncer then logs `got packet 'A' from server when not linked` for each change, and its other clients can see read timeouts. After upgrading, run `RECONNECT` on PgBouncer's admin console, or restart it, so the server connections that still hold that `LISTEN` are closed; otherwise they close at the latest after `server_lifetime` (an hour by default). ## Several applications on one schema Applications can share one database and one SyncLane schema. Each declares its own queues, so jobs, planning and clean-up stay separate, and a budget declared by several applications is shared by all of them. One table then shows every sync of every application. Each process registers in `instances` at start-up and every half minute after. Its row holds: - its application, and its role when it sets one (`options.Role`); - its host; - the SyncLane version; - the queues it runs with its planner or workers, and whether it runs workers, the planner and listening; - what it declares: every job type with its queue and handler; - its budgets. Its id is the host, the process id and a random part, so two containers that share a hostname and both run as process 1 are still two rows. The application is `options.Application`. It defaults to the host's application name, which is the entry assembly's unless the host sets another. Copies of one application share their queues. **A queue belongs to one application at a time.** A worker takes any job of a queue it declares, so two applications on one queue would take each other's jobs and abandon the types they do not know (`SL4001`). An instance that would run a queue a live instance of another application runs does not start, and says which one (`SL1011`). Rename the queue in one of them, or give both the same `Application` if they are one application. - An instance that runs neither the planner nor workers claims no queue. It can declare any queue to call `ISyncLane` on it, for example from an admin application. - An instance that stops marks its row stopped (`stopped_at`) and no longer holds its queues. One that dies without stopping counts as gone two minutes after its last heartbeat. Either row is deleted a day after its last heartbeat, so "was the service down last night?" has an answer the next morning: ```sql SELECT application, host, started_at, heartbeat_at, stopped_at FROM synclane.instances ORDER BY application, started_at; ``` - **Each application needs a name of its own.** The default name is the entry assembly's, and projects built from one template often share it (`Api`, `WebApi`). Two applications under one name are one application to SyncLane: one switch turns both on and off, and the monitor shows them as one. So each instance also records what it declares, every job type with its queue and handler, whether it runs them or not, and with each heartbeat compares it with the live instances of its name. One that declares nothing in common with it is reported in the log, in the health check (Degraded) and in the instances list (`InstanceInfo.SharesNameWith`, `GET /instances`). Copies, web instances and a deploy that adds or removes a queue keep most of it in common and are not reported. Set `SyncLane:Application` in each application's settings to a name of its own, and start its queue names with it (`shop.orders`), so neither the name nor the queues can meet another's. - A budget that another live instance declares with another limit, period or burst is logged as a warning at start-up: instances that disagree pace a shared budget differently. During a deploy that changes a limit this passes by itself. - Instances of SyncLane versions before the instances table do not register, so they are not seen by this check. ## Upgrading the schema The schema is a numbered list of migrations. `synclane.migrations` records which ones a database has. With `CreateSchema` on, each instance applies what is missing at start-up, in one transaction, behind a lock; instances that start together wait for each other, and the second one finds nothing to do. Migrations are only ever added, and each one only adds. An instance still running the previous version keeps working against the upgraded table, so you can roll a deploy one instance at a time. A table created by SyncLane 0.1, before the migrations table existed, is adopted as it is: migration 1 finds the table and indexes in place and only records itself. Migrations 5 and 14 build indexes on `jobs`, and a plain `CREATE INDEX` blocks writes to the table while it runs. On a large table, create them first without blocking. The migration then finds them and skips them: ```sql CREATE INDEX CONCURRENTLY IF NOT EXISTS jobs_open ON synclane.jobs (queue, owner, type) WHERE status <> 'completed'; CREATE INDEX CONCURRENTLY IF NOT EXISTS jobs_finished ON synclane.jobs (queue, completed_at) WHERE status = 'completed' AND mode <> 'initial'; CREATE INDEX CONCURRENTLY IF NOT EXISTS jobs_lease_order ON synclane.jobs (queue, (status = 'deferred'), priority, window_start DESC NULLS LAST, next_run_at, id) WHERE status <> 'completed'; ``` `jobs_lease_order` covers only jobs that have not completed, so even on a table with a long history it is usually built in a moment. ## Running the schema yourself Set `CreateSchema = false` and put the script into your own migrations. `SyncLaneSchema.Script()` returns it for any schema name; with EF Core that is one line: ```csharp migrationBuilder.Sql(SyncLaneSchema.Script("synclane")); ``` When a SyncLane upgrade brings a new migration, add a new migration of your own with the same line. The script is safe to run on a database that already has some or all of it. [schema.sql](schema.sql) is the same script for the default schema, checked against the library by a test. With `CreateSchema` off SyncLane never changes the database. It checks at start-up that every migration it knows is recorded, and if one is missing it stops the host with a message that names the migration and the call that produces it. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/production-trial.md # Production trial Before you rely on SyncLane, run one real integration with it for 30 days. This page is the checklist for that trial: what to set up, what to break on purpose, what to watch and when to stop. ## Before the first run - [ ] **Pick one integration that is allowed to fail.** One provider, a handful of accounts, data you can reload. Not the integration your business depends on today. - [ ] **Keep the old path running beside it** for the first two weeks, writing to a different table, so you can compare record counts. - [ ] **Start slow.** `Concurrency = 1` per queue, a `slice` of 7 days, a `horizon` of 30 days. Raise them after the first week if nothing complains. - [ ] **Make every write an upsert.** A page can be handled twice (see "What it promises" in the README). - [ ] **Throw `JobThrottledException` on `429`**, with the provider's `Retry-After` when it sends one, and `JobAbandonedException` when access was revoked. - [ ] **Wire metrics and traces** (see [operations.md](operations.md#metrics-and-traces)) and set the three alerts listed there. - [ ] **Decide who owns the schema.** Either `CreateSchema = true`, or `SyncLaneSchema.Script()` in your own migration. - [ ] **Read [SECURITY.md](../SECURITY.md)**, especially the part about what ends up in the `error` column. ## Drills, in the first week Run each once and write down what happened. | Drill | How | Expected | | --- | --- | --- | | Graceful stop | Stop the app while a job is running. | The job is `pending` again with its cursor; the log says it was handed back. | | Crash | `kill -9` the process while a job is running. | After `LeaseDuration` another instance (or the restarted one) takes the job and continues from the cursor. `lease_lost` stays at zero. | | Rolling deploy | Deploy a new build one instance at a time while jobs run. | No job runs twice at once; no migration error. | | Two instances | Run two instances against the same table for a day. | Every job is created once; never two running jobs in one lane. | | Provider outage | Point one account at a wrong host for an hour. | Its jobs fail, back off, defer and finally abandon. Other accounts are not slowed down. Requeue brings it back from the cursor. | | Revoked access | Revoke one account's token. | Its jobs end `abandoned` after one attempt if the handler throws `JobAbandonedException`. | ## Every day One query and one look at the dashboard: ```sql SELECT status, count(*) FROM synclane.jobs WHERE updated_at > now() - interval '1 day' GROUP BY status; ``` - Anything `abandoned`: read the `error`, fix the cause, requeue. - `synclane.job.throttled` rising: lower `Concurrency` or widen `every`. - `synclane.job.wait` rising: more worker slots, or a lane that never gets idle. ## Keep a log One line per incident in a file next to the integration: date, what happened, which job ids, what fixed it, and whether it was SyncLane's fault, the handler's or the provider's. The log is what tells you, at the end, whether SyncLane is ready for the next integration. ## Exit: the trial is done when - 30 days have passed with no data lost and no job run twice at the same time in one lane; - every drill above has been run and behaved as expected; - record counts match the old path for the two weeks they ran side by side; - every incident in the log has a cause. ## Stop: pause new features when - a job's cursor was lost or went backwards; - two jobs of one lane ran at the same time; - a migration failed on start-up. Any of these is a bug in the core. Fix it, add a test that reproduces it, and restart the 30 days. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/monitoring.md # Watching it run How to see what SyncLane does: the monitor's questions, live changes, the HTTP endpoints, metrics and traces, and health checks. Repairs and SQL for everything else are in [operations.md](operations.md). `ISyncLaneMonitor` answers what an operator asks, for every queue in the schema, whichever application runs it: | Call | Answers | | --- | --- | | `GetOverviewAsync()` | One line per queue: due, postponed, running, retrying, deferred and abandoned jobs; owners; live instances; jobs, records and failures in the last 24 hours. | | `GetFreshnessAsync(query)` | Owners ranked by how old their newest completed data is, each with the job that explains it (its status, error code and next run) and how much of its history has loaded. `Search` finds owners by name or key. | | `GetFreshnessOwnersAsync(query)` | The same rows grouped by owner across the queues you name, the owner with the oldest data first, so a page never cuts an owner in half. `Show` keeps only the rows, and so the owners, that are stale, need attention (an open job failed, was deferred or abandoned) or are paused. `IncludeTotal` counts the owners. | | `GetJobOwnersAsync(query)` | Each owner's jobs counted by status (pending, running, completed, failed, deferred, abandoned) across the queues you name, one row per owner, the owner with the newest job first. `Status` and `Type` narrow the counts, `Search` finds owners by name or key, `IncludeTotal` counts the owners. | | `GetProblemsAsync(queue?)` | Failing, deferred and abandoned jobs grouped by error code: "SL5106: 37 jobs, 12 owners" instead of 37 rows. | | `GetBudgetsAsync(query)` | Each rate budget and key: the rate it learned, the limit the API reports and any operator's limit, whether it is paused, when it was last refused. `Search` finds buckets whose budget name or key contains the text, ignoring case; `IncludeTotal` also counts the matching buckets into `Total`, for a pager that shows "page 2 of 7". | | `GetInstancesAsync()` | Every process of every application: host, role, version, queues, whether it runs workers, the planner and listening, and whether it is alive, stopped (and when) or gone without stopping. Stopped and gone ones stay listed for a day. `SharesNameWith` names live instances under the same application that declare none of its queues and job types: most likely another application that took the same name. `FollowsSwitches` is false for an instance of a version that does not read switches. | | `GetSwitchesAsync()` | Each application and role: the switch an operator set, if any, how many of its live instances run workers and the planner, and how many run a version that ignores switches (`IgnoringSwitch`). | | `GetVolumeAsync(query)` | Completed jobs, records, failed attempts and abandoned jobs per hour or day, kept for 400 days. | ```csharp var behind = await monitor.GetFreshnessAsync(new FreshnessQuery { Queue = "shops", Limit = 20 }); foreach (var row in behind.Items) Console.WriteLine($"{row.Owner} {row.Type}: data until {row.DataUntil:u}, {row.Status} {row.Code}"); ``` An owner is known by its key on one queue. When an integration runs a queue per kind of data with the same owner keys on each, name those queues and each account comes once, with a row per queue and job type. A row is stale when its completed data is older than `StaleAfter` (24 hours by default) or it has completed nothing yet: ```csharp var owners = await monitor.GetFreshnessOwnersAsync(new FreshnessOwnerQuery { Queues = ["shops", "shops.products"], Show = FreshnessShow.Attention, IncludeTotal = true }); Console.WriteLine($"{owners.Total} owners need a look"); foreach (var owner in owners.Items) Console.WriteLine($"{owner.OwnerName ?? owner.Owner}: {string.Join(", ", owner.Rows.Select(row => $"{row.Queue} {row.Type} {row.Code}"))}"); ``` An owner is known by its key on each queue, so `GetJobOwnersAsync` takes the queues whose owner keys mean the same accounts, such as the queues of one integration, and counts each owner's jobs on all of them together; leaving `Queues` out is refused (`SL3016`). A page costs about the same at any depth, so a screen can show "page 2 of 7" with `IncludeTotal` on its first page: ```csharp var owners = await monitor.GetJobOwnersAsync(new JobOwnerQuery { Queues = ["shop.orders", "shop.stock"], IncludeTotal = true }); foreach (var owner in owners.Items) Console.WriteLine($"{owner.OwnerName ?? owner.Owner}: {owner.Failed} failed, {owner.Abandoned} abandoned, last job {owner.LastJobAt:u}"); ``` The counts are of the jobs still in the table. Completed recurring and manual jobs are deleted after `KeepCompletedJobs` (7 days by default), and initial jobs are kept, so `Completed` counts the completed recurring and manual jobs of that last week and every completed initial job; `GetVolumeAsync` counts completions for 400 days. `WatchAsync(queue?, owner?)` streams jobs as they are created and change status, from every instance, a moment after each change commits, so a live view or an alert needs no polling: ```csharp await foreach (var change in monitor.WatchAsync("shops", cancellationToken: stopping)) await hub.Clients.All.SendAsync("job", change.Id, change.Owner, change.Status.ToString(), stopping); ``` Over HTTP, `SyncLane.AspNetCore` maps all of it in one line, with the stream as server-sent events. The endpoints show up in your OpenAPI (Swagger) document under `SyncLane`, and answer only requests from the same machine until you require authorization: ```csharp app.MapSyncLane("/synclane").RequireAuthorization("ops"); ``` See [the package's readme](../src/SyncLane.AspNetCore/README.md) for the routes. `SetSwitchAsync(application, role, runWorkers, runPlanner, reason)` turns an application's workers and planner on or off without a deploy, and `SetListeningAsync(application, role, listen, reason)` its listening connections ([Switching an application on and off](operations.md#switching-an-application-on-and-off)). It also has an emergency stop, `PauseAsync(queue, owner?, reason)`, which cuts what runs on every instance and takes nothing more until `ResumeAsync`, and the repairs the answers call for: `RequeueJobAsync(id)`, `RestartJobAsync(id)` to fetch a window again, `RequeueByCodeAsync(queue, code)` after fixing what a problem group shows, `PrioritizeOwnerAsync(queue, owner)` for an account that should load first, and `SyncNowAsync(queue, owner, type)` when the other side announces a change, for example with a webhook: it fetches from where the owner's data reaches to now, at high priority, and a burst of calls is one fetch. `LimitBudgetAsync` lowers a rate budget for a while. Every action is logged with who did it and why, and `GetActionsAsync(query)` lists the log newest first: `Search` finds text in the action, queue, owner, target, reason or who did it (ignoring case, 1 to 100 characters), and `IncludeTotal` also counts every match, so a screen can show "page 2 of 7" (`total` over HTTP, with `includeTotal=true`). See [docs/operations.md](operations.md#changing). Each read except the job owners read is one round trip that reads small summary tables and the open jobs, never the history: on a table of a million jobs each one takes about a millisecond, a page of 50 owners grouped across two queues about 6, and a year of daily volume about 45. The job owners read is one round trip too, but it counts the kept jobs of the owners on its page, through `owners` and an index, never the whole table: about 25 ms for a page of 50 owners out of a thousand. Lists page with a cursor. `Total` is counted only when the query sets `IncludeTotal`, in the same round trip as the page; ask for it on the first page of a screen, not on every page. Searching budgets and counting them reads the small `rate_buckets` table (one row per budget and key): about 2 ms for 5,000 rows and 19 ms for 50,000. SyncLane also reports metrics and traces through the APIs built into .NET, so it adds no dependency and costs nothing when nobody listens. With OpenTelemetry: ```csharp builder.Services.AddOpenTelemetry() .WithMetrics(metrics => metrics.AddMeter(SyncLaneTelemetry.MeterName)) .WithTracing(tracing => tracing.AddSource(SyncLaneTelemetry.ActivitySourceName)); ``` Every run of a job is a `synclane.job` span and every page a `synclane.page` span inside it, so the HTTP calls your handler makes show up under the page that made them. The metrics count jobs taken and finished by outcome, pages, records, throttles and planner runs, and time how long jobs wait and run. Tags name the queue and the job type, never the owner or the lane. Without OpenTelemetry, `dotnet-counters monitor --counters SyncLane` shows them live. The full list is in [docs/operations.md](operations.md#metrics-and-traces). ## Health checks `AddSyncLane` provides `SyncLaneHealthCheck` for .NET's health checks, in a web app or a worker: ```csharp builder.Services.AddHealthChecks().AddCheck("synclane"); app.MapHealthChecks("/health"); ``` - **Unhealthy** when the database cannot be reached, its schema lacks migrations this version needs, or this instance has not renewed its registration for two minutes, after which other instances count it as gone. - **Degraded** while it starts, when the latest planning round of a queue failed, or when it does not hear job changes (behind a pooler in transaction mode without `ListenConnectionString`, or while it reconnects). Workers still find jobs by polling then. - Each check is one small query. Descriptions say what is wrong and how to fix it; they never hold a connection string or an exception's message. --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/src/SyncLane.AspNetCore/README.md # SyncLane.AspNetCore HTTP endpoints for SyncLane's monitor, in one call. They appear in your application's OpenAPI (Swagger) document under the tag `SyncLane`. ```csharp builder.Services.AddSyncLane(options => { /* ... */ }); app.MapSyncLane("/synclane").RequireAuthorization("ops"); ``` | Method | Path | What it answers | | --- | --- | --- | | GET | `/overview` | One line per queue: open jobs by state, owners, instances, the last day | | GET | `/freshness?queue=&owner=&search=&limit=&cursor=` | Owners ranked by how old their completed data is, with the job that explains it; `search` finds owners by name or key | | GET | `/freshness/owners?queues=&search=&show=&staleAfter=&limit=&cursor=&includeTotal=` | The same, grouped by owner across the queues named (repeat `queues`), stalest owner first, so a page never cuts an owner in half; `show` is `all`, `attention`, `stale` or `paused`, `staleAfter` as `1.00:00:00`; `includeTotal=true` counts the owners into `total` | | GET | `/problems?queue=` | Failing and abandoned jobs grouped by error code | | GET | `/budgets?budget=&search=&includeTotal=&limit=&cursor=` | Rate budgets: learned rate, pause, last refusal; `search` finds budgets by name or key; `includeTotal=true` adds `total`, the number of matching buckets | | GET | `/instances` | Every process of every application on the schema: alive, stopped (with when) or gone | | GET | `/volume?from=&to=&queue=&type=&unit=hour` | Completed jobs, records, failures per hour or day | | GET | `/jobs?queue=&owner=&status=&type=&search=&limit=&cursor=` | Jobs, newest first, with each owner's name; `search` finds owners by name or key | | GET | `/jobs/owners?queues=&queues=&status=&type=&search=&limit=&cursor=&includeTotal=` | Each owner's jobs counted by status across the queues given (one `queues=` per queue, at least one), newest job first; `includeTotal=true` adds `total`, the number of owners | | GET | `/stream?queue=&owner=` | Server-sent events, one `job` event per created job or status change | | GET | `/pauses` | The pauses in force: who, why, until when | | GET | `/budget-limits` | The budget limits in force: who, why, until when | | GET | `/switches` | Each application and role: its switch, how many live instances run workers and the planner and listen, and how many ignore switches because they run an older version | | GET | `/actions?queue=&owner=&search=&limit=&cursor=&includeTotal=` | What operators did, newest first, with who and why; `search` finds text in the action, queue, owner, target, reason or who did it; `includeTotal=true` adds `total`, the number of matches over every page | | POST | `/pause?queue=&owner=&reason=&until=` | Emergency stop of a queue or one owner: running jobs are cut and handed back | | POST | `/resume?queue=&owner=` | Lift a pause | | POST | `/budgets/limit?budget=&key=&limit=&per=&reason=&until=` | Lower a rate budget, or one key of it, for a while (`per` as `00:01:00`) | | POST | `/budgets/clear-limit?budget=&key=` | Lift a budget limit | | POST | `/jobs/{id}/requeue`, `/jobs/{id}/restart` | Repair one job | | POST | `/jobs/{id}/skip?reason=` | Take one job out of line for good, so an ordered lane goes on | | POST | `/requeue-by-code?queue=&code=` | Requeue every failing job with one error code | | POST | `/prioritize?queue=&owner=` | Move an owner's waiting jobs ahead of the others | | POST | `/switch?application=&role=&workers=&planner=&reason=` | Turn an application's workers and planner on or off without a deploy; leave `workers` or `planner` out to follow its settings | | POST | `/switch/listen?application=&role=&listen=&reason=` | Turn an application's listening connections on or off without a deploy; leave `listen` out to follow its settings. The workers and the planner keep their switch | | POST | `/sync-now?queue=&owner=&type=` | Fetch an owner's new data now, for example on a webhook; a burst of calls is one fetch | Safe by default: - Until the group requires authorization, the endpoints answer only requests from the same machine. A request that came through a proxy (`X-Forwarded-For` and the like) does not count as local. - Repairs need the header `X-SyncLane-Action`, which a page on another site cannot send. `MapSyncLane(configure: o => o.ReadOnly = true)` leaves them out. - Answers are never cached and never hold a job's cursor, which can contain the other side's token. - Each pause, budget limit and repair is written to the actions log with the signed-in user who asked for it. The stream needs `LISTEN`, which a pooler in transaction mode cannot carry: set `ListenConnectionString` to the server itself. More: [the monitor](https://github.com/synclane-dev/synclane/blob/main/docs/monitoring.md), [error codes](https://github.com/synclane-dev/synclane/blob/main/docs/errors.md). --- Source: https://raw.githubusercontent.com/synclane-dev/synclane/main/docs/demo.md # The demo The demo syncs four pretend shop accounts. The pretend shop answers slowly, sometimes returns 429 or 503, and one page of one account is broken on purpose. ```bash docker compose up --build ``` Open .

The demo page about fifteen seconds after start: four accounts with their progress, three jobs running in three lanes, five jobs waiting for a retry with their cursors and errors, and the remaining slices of history pending.

Things to watch for: - **Lanes.** `acme-us` and `acme-eu` share the lane `acme` and take turns. `globex` and `initech` run beside them. - **Newest first.** Each account's orders arrive from the most recent month backwards. - **Retries.** Jobs that hit a 429 or 503 turn `failed`, wait, and continue from the cursor they had reached. - **Giving up.** One slice of `globex` fails on its second page every time. After five attempts it is `deferred`, the rest of the lane finishes, it gets its last attempt and ends `abandoned` with cursor `50`. - **Requeue.** Press *Requeue stopped jobs*. The broken page has healed by then, and the job completes from cursor `50`, not from the start. - **Restart.** Run `docker compose restart demo` during the first minute. The jobs that were running are `pending` again with their cursors, and continue after the restart. The same information without the page: ```bash docker compose exec postgres psql -U postgres -d synclane \ -c "select id, owner, type, status, cursor, processed_count, attempt_count, error from synclane.jobs order by id" ```
Without Docker You need the .NET 10 SDK and a PostgreSQL database the demo may create two schemas in (`synclane` and `demo`): ```bash ConnectionStrings__Postgres="Host=localhost;Username=postgres;Database=synclane" \ ASPNETCORE_URLS=http://localhost:8080 dotnet run --project samples/Demo ```