Skip to content

Deployment shapes

How the same Sypnia binary runs as three AWS functions or as one long-running process, what the AWS template creates, what each shape costs with the arithmetic shown, and the pieces you can swap, seen from the code.

Applies to Engine
View as Markdown
On this page
  1. One engine, two ways to wake it
  2. As AWS functions
  3. Why a queue, and only one
  4. What the template creates
  5. Cold starts, limits and connections
  6. What it costs on AWS
  7. As one long-running process
  8. The pieces you can swap
  9. Which shape to choose
  10. What changed from the system this comes from
  11. Next

The engine is one program, sypnia. It can be started in two ways, and it does the same work in both:

  • as functions on AWS, woken by requests, a queue and a schedule;
  • as one long-running process, in Docker or on any server.

This page shows what differs between the two, what is the same, what each costs, and where the engine’s edges are: the four pieces you can replace.

One engine, two ways to wake it

Figure. The same engine in both shapes. On AWS a queue stands where the in-memory buffer is; nothing else differs.
  1. The intake queue: on AWS it stands between the ingest function and the worker.
  2. The buffer, flushed every 2 seconds: on a server it does the queue’s job, in memory.
  3. The engine: the same code in both shapes.
Read this diagram as text

Three columns. In the centre, the engine with its five parts: Ingest; Fast path; Roll-up; The agent and Alerts; API, MCP server and Console. On the left, AWS runs it as three functions. ingest is triggered by HTTPS through the address and runs Ingest. worker is triggered by the queue (a 10-second window), by the schedule every minute and by itself for agent jobs; it runs the Fast path, the Roll-up, the agent and Alerts. api is triggered by HTTPS through the address and runs the API, the MCP server and the Console. On the right, a server runs one process, sypnia serve, with four tasks: the HTTP server (Ingest, and the API, MCP server and Console), the buffer (Ingest), the worker loop every 30 seconds (Fast path, Roll-up, the agent and Alerts) and the cache refresh every 60 seconds. Under both, the same Bucket and the same Postgres: the same bucket layout and the same tables, so you can move from one shape to the other.

AWS functionsOne process
Started byThe templatesypnia serve
Ingest’s buffer (1) (2)A queue: ingest sends, the worker writes the segmentMemory: flushed every 2 s
The fast path runsWhen the queue delivers, and every minuteWhen a segment lands, and every 30 s
The roll-up runsOn the minute tick, when 5 minutes have passedIn the worker loop, when 5 minutes have passed
Scales byMore copies of a function, by itselfMore processes with --role, by you
Idle costAlmost nothingThe server
Bucket layout and tablesThe sameThe same

Both start in the same main. Notice that there is one Engine::connect and that everything after it only decides what wakes the engine up.

crates/sypnia/src/main.rs
#[tokio::main]
async fn main() -> ExitCode {
    let config = match Config::from_env_and_file() {
        Ok(config) => Arc::new(config),
        Err(error) => return fail(3, &error), // a missing required setting names itself
    };
    // Bucket, Postgres, the AI provider (or none), the alert sinks. Built once, shared by everything.
    let engine = match Engine::connect(config.clone()).await {
        Ok(engine) => Arc::new(engine),
        Err(error) => return fail(4, &error),
    };

    // Inside AWS Lambda the runtime sets this variable and there is no command line.
    if std::env::var_os("AWS_LAMBDA_RUNTIME_API").is_some() {
        return exit(lambda::run(engine, config.role).await);
    }

    match Cli::parse().command {
        Command::Serve(args) => exit(serve::run(engine, args).await),       // the long-running process
        Command::Aggregate(args) => exit(aggregate::run(engine, args).await), // one pass, then exit
        Command::Migrate(args) => exit(migrate::run(engine, args).await),
        Command::Doctor => exit(doctor::run(engine).await),
        other => exit(admin::run(engine, other).await), // project, key, token, sourcemaps, problems
    }
}

As AWS functions

The template runs one function per role, the same three roles sypnia serve --role accepts.

Figure. What the template creates: one address, three functions, one queue with its dead-letter queue, one schedule and a bucket. Postgres is yours to bring, or the instance of the database stack, `sypnia-db`.
  1. ingest: 256 MB, 10 s, arm64. It may only put objects in the Bucket.
  2. The intake queue, with its dead-letter queue after 5 failed deliveries.
  3. worker: 1,024 MB, 15 min, arm64. It reads and writes the Bucket and Postgres, and invokes itself for agent jobs.
  4. api: 512 MB, 30 s, arm64. The API, the MCP server and the Console. It reads Postgres, and reads and signs links to the Bucket.
  5. The schedule: every minute. It also starts the daily job at 02:30 UTC and the weekly one on Monday 07:00 UTC.
  6. The address, https://sypnia.example.com: /v1/ingest/*, /v1/otlp/* and the SDK’s two script files (/v1/sdk.js, /v1/sdk-recorder.js) go to ingest, everything else to api.
Read this diagram as text

Inside the frame «Your AWS account · one region». Your app (SDK) sends events, replay chunks and OTLP to the address; you and your coding agent use the same address. ingest sends validated batches to the intake queue, and replay chunks, snapshots and large batches straight to the Bucket. The queue delivers up to 10 seconds of messages to the worker, which writes segments, session files and Parquet to the Bucket, and problems, numbers and the ledger to Postgres. The Bucket is private and every key starts with a project id; Postgres is yours, or created by the template. Outside the frame, the worker calls your AI provider (the agent, if configured) and your webhook (alerts).

Function (role)Woken byDoesMemory, time limit
ingest (1)The address (6), for /v1/ingest/*, /v1/otlp/* and the SDK’s two script files (/v1/sdk.js, /v1/sdk-recorder.js)The seven gates, then sends the validated batch to the queue. Writes replay chunks, snapshots and batches over 192 KiB straight to the Bucket256 MB, 10 s, at most 40 copies
worker (3)The intake queue (2): up to 10 seconds of messagesWrites the segments, adds the ledger rows, runs the fast path on them at once, under the same 2-minute lease as the minute tick so the two never scan a segment twice1,024 MB, 15 min, at most 3 copies, of which the queue uses up to 2
The schedule, every minute (5)One pass: the fast path’s leftovers and held failures, alerts past their time, uptime checks, webhook retries, and the roll-up when 5 minutes have passed
Itself, asynchronouslyOne agent job: symbolicate, analyse, release the alert. And the two long jobs the pass starts when they are due: the daily one at 02:30 UTC (Parquet, retention, next months’ partitions) and the weekly suggestions on Monday at 07:00 UTC
api (4)The address (6), for everything elseThe API, the MCP server at /mcp, the Console at /console512 MB, 30 s, at most 20 copies

The worker tells its wake-ups apart by the shape of the event. Notice that the queue case and the one-process buffer end in the same two calls: write segments, scan them.

crates/sypnia/src/lambda.rs
/// Everything that can wake the worker function.
#[derive(Deserialize)]
#[serde(untagged)]
enum WorkerEvent {
    Queue(SqsEvent),       // { "Records": [...] }: batches from the ingest function
    Job { job: Job },      // { "job": "pass" }: a schedule, or the worker calling itself
}

#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
enum Job {
    Pass,
    Daily,
    Suggestions,
    Agent { problem: ProblemId },
}

async fn worker_event(engine: &Engine, event: WorkerEvent) -> Result<WorkerAnswer, EngineError> {
    match event {
        WorkerEvent::Queue(batch) => {
            // The same two steps the in-memory buffer ends with: write segments, scan them.
            // The answer names the messages that could not be written; only those are delivered again.
            return Ok(WorkerAnswer::Queue(intake_batch(engine, batch).await));
        }
        WorkerEvent::Job { job: Job::Pass } => { engine.pass().await?; }
        WorkerEvent::Job { job: Job::Daily } => daily::run(engine).await?,
        WorkerEvent::Job { job: Job::Suggestions } => suggestions::run(engine).await?,
        WorkerEvent::Job { job: Job::Agent { problem } } => agent::run_job(engine, &problem).await?,
    }
    Ok(WorkerAnswer::Done) // a job that failed is a row in Postgres: the next pass finds it
}

pub async fn run(engine: Arc<Engine>, role: Role) -> Result<(), lambda_runtime::Error> {
    match role {
        Role::Ingest => lambda_http::run(ingest::router(engine)).await, // the same axum router as `serve`
        Role::Api => lambda_http::run(api::router(engine)).await,
        Role::Worker | Role::All => {
            lambda_runtime::run(service_fn(move |event: LambdaEvent<WorkerEvent>| {
                let engine = engine.clone();
                async move { worker_event(&engine, event.payload).await }
            }))
            .await
        }
    }
}

Why a queue, and only one

The queue (2) exists for one reason: a function has no memory between requests, so it cannot group batches into segments. The queue is that memory. It also wakes the worker the moment there is something to scan, which is why the AWS shape creates a problem faster than its one-minute schedule would suggest.

There is one queue and not four. Agent jobs, alert releases and webhook retries are rows in Postgres with a time on them; the minute tick picks up whatever a direct call missed. The alternative, a queue per kind of work, would be three more things to create, watch and pay for, to move a few rows a minute.

A message that the worker cannot write is delivered again after 15 seconds, 1 minute, 5 minutes and 15 minutes. After the fifth delivery it goes to the dead-letter queue, where it is kept 14 days, and an alarm fires. Nothing in the engine reads that queue by itself: a batch that cannot be written five times is a bug to look at or an outage to wait out. When the cause is gone, one command sends the messages back to the intake queue (a redrive), and a batch that had in fact been written is skipped by its batch_id. The message’s whole life, the command and the alarms are on What happens when something fails.

What the template creates

ResourceNotes
A private bucketNo public access. One lifecycle rule, for unfinished uploads. Retention is the engine’s daily job
The intake queue and its dead-letter queueMessages kept 4 days; 5 deliveries before the dead-letter queue, which keeps them 14 days
Three functions, arm64, with their rolesingest may send to the queue and put objects; api may read objects and sign links; worker may read and write the bucket and call itself
One addressA content-delivery distribution in front of the two HTTP functions, so the engine has one base URL. It caches nothing but the SDK’s two script files. CORS is answered by the engine, not by the address
One scheduleEvery minute. The daily and weekly jobs are started by the pass when they are due, so there is one schedule to watch, not three
Log groupsKept 30 days
Three alarmsMessages in the dead-letter queue; the oldest message in the intake queue older than 2 minutes; the worker failing
Postgres, in a stack of its ownA small instance shared by databases of their own (sypnia-db.yaml), or none if you pass SYPNIA_DATABASE_URL

It does not create a load balancer, a container cluster, a cache, a stream or a search service. The step-by-step guide is Deploy on AWS. The same deployment with the AWS service names on, its limits, an excerpt of the template and what each service costs is A reference implementation on AWS.

Cold starts, limits and connections

  • Cold starts. The binary is native code with no runtime to boot and nothing to download. Budget: 300 ms for a cold function to answer its first request, most of it opening the connection to Postgres. For comparison, measured on the system this comes from: 0.4 s for its aggregator to start, and then a 50 MB extension download on every cold start, which this design does not have.
  • The 6 MB answer. A function cannot answer more than 6 MB. The same rules as there: a replay is delivered as signed links to its chunks, never through the function; a session’s detail has a budget of 4 MB with a fixed order of what to leave out.
  • Connections to Postgres. Each copy of a function holds its own. ingest holds at most one and uses it only to fill its cache; api at most two; a worker one per project it is rolling plus one. Put a connection pooler in session mode in front of Postgres when many copies run (the engine prepares its statements, which a transaction-mode pooler breaks): the system this comes from exhausted its pooler once, with every copy of a request-serving function opening its own pool.
  • The ingest cache. A cold ingest function asks Postgres for a key the first time it sees it, then keeps it for 60 seconds. A warm one never asks.

What it costs on AWS

Two example projects. Small is the size measured on the system this engine comes from. Medium is ten times that.

Per monthSmallMedium
Events4 million (130,000 a day)40 million
Sessions30,000 (1,000 a day)300,000
Batches sent to ingest (30 a session)0.9 million9 million
Replay chunks (15 % of sessions recorded × 22 chunks)0.1 million1 million

Prices used, on demand, as published for us-east-1 when this was written: functions on arm64 USD 0.0000133 per GB-second and USD 0.20 per million requests; queue USD 0.40 per million requests; object storage USD 0.023 per GB-month, USD 5 per million writes, USD 0.40 per million reads; logs USD 0.50 per GB. Check them before you rely on a total.

LineArithmetic (small)SmallMedium
The address1.0 M requests. Inside the provider’s free allowance of 10 million requests a month; about USD 1 per million beyond it0.000.00
ingest requests1.0 M × 0.200.202.00
ingest time1.0 M × 0.05 s × 0.25 GB = 12,500 GB-s0.171.67
Queue0.9 M sends + about 0.6 M receives and deletes = 1.5 M × 0.400.604.00
worker, queue wake-upsAt most one every 10 s: 260,000 × 0.5 s × 1 GB = 130,000 GB-s (2 s each at medium)1.786.98
worker, minute tick43,200 × 1 s × 1 GB (2 s at medium)0.581.15
worker, roll-up8,640 runs × 5 s × 1 GB (30 s at medium)0.583.46
Object writes260,000 segments + 60,000 session files + 100,000 chunks = 0.42 M × 52.1010.50
Object readsThe roll-up re-reads the open hour: at most 3.1 M × 0.401.242.00
Object storage1.2 GB per million events; 90 days of events, 30 of replays: about 8 GB × 0.0230.181.84
LogsSuccesses sampled at 1 %: about 1 GB0.502.00
Engine, without Postgres≈ USD 8≈ USD 36
PostgresThe smallest managed instance with 1 GB of memory and 20 GB of disk; 2 to 4 GB of memory and 50 GB of disk at medium≈ 1425 to 50
Total≈ USD 22≈ USD 60 to 85

Three things to read from the table:

  1. The database is the largest single line at small sizes. It is also the one you may already have: any Postgres 15 or later works.
  2. Object writes cost more than everything stored. Measured there: of USD 3.81 of object storage in 12 days, USD 2.73 was writes. This is why batches are grouped into segments and why replay chunks are 200 KB and not smaller.
  3. Receiving is nearly free. A million batches cost less than 40 cents to accept.

The AWS free allowance for functions, 400,000 GB-seconds and a million requests a month, covers almost all the function lines of the small project. The small total agrees with what the first deployment of this design costs, USD 15 to 25 a month.

Not in the table: the model. An analysis is a few thousand tokens in and at most two thousand out, at most 100 a day per project, at your provider’s price. And data leaving AWS when you watch replays, which is the size of the replay.

The same bill seen from the other side, as a cost per batch, per million events, per replay and per analysis, with the idle cost of a deployment and two small fixed items this table leaves out (alarms, the database’s public address), is the cost model of the reference implementation.

As one long-running process

sypnia serve is the whole engine in one process: the HTTP server for ingest, the API, the MCP server and the Console, and the worker.

Task inside the processDoesEvery
HTTP serverIngest, OTLP, API, MCP server, ConsoleEach request
Buffer flusherCloses open segments, writes them, queues their ledger rows2 s, or 4 MiB
Worker loopEngine::pass: fast path, alerts, uptime, and the roll-up when dueprocessing.interval_seconds, 30 s; at once when a segment lands
Agent tasksOne per job, at most 4 at a timeWhen the fast path queues one
Cache refreshKeys, origins, limits, slow_down60 s
Daily taskParquet, retention, partitions02:30 UTC

Notice in the excerpt that the worker loop waits for whichever comes first, the timer or a segment landing, and that shutdown lets the current step finish.

crates/sypnia/src/serve.rs
pub async fn run(engine: Arc<Engine>, args: ServeArgs) -> Result<(), ServeError> {
    let stop = CancellationToken::new();
    let mut tasks = JoinSet::new();

    if args.role.serves_http() {
        let app = Router::new()
            .merge(ingest::router(engine.clone()))  // /v1/ingest/*, /v1/otlp/*, /v1/sdk.js, /v1/sdk-recorder.js
            .merge(api::router(engine.clone()));    // /v1/*, /mcp, /console, /healthz
        let listener = TcpListener::bind(engine.config.listen).await?;
        let stopping = stop.clone();
        tasks.spawn(async move {
            axum::serve(listener, app)
                .with_graceful_shutdown(async move { stopping.cancelled().await })
                .await
                .map_err(ServeError::from)
        });
    }

    if args.role.works() {
        let (engine, stopping) = (engine.clone(), stop.clone());
        tasks.spawn(async move {
            let every = engine.config.processing.interval;
            loop {
                if let Err(error) = engine.pass().await {
                    tracing::error!(%error, "pass failed; the next one repeats it");
                }
                tokio::select! {
                    _ = tokio::time::sleep(every) => {}
                    _ = engine.segment_landed.notified() => {} // do not make a failure wait 30 s
                    _ = stopping.cancelled() => return Ok(()),
                }
            }
        });
    }

    shutdown_signal().await; // SIGTERM or Ctrl-C
    stop.cancel();           // requests get 20 s; open segments are flushed; the pass finishes its step
    while let Some(done) = tasks.join_next().await {
        done??;
    }
    Ok(())
}

Sizing. The engine’s process needs memory for two projects being rolled (2 × 256 MB), the ingest buffer (32 MiB) and the source-map cache (200 MB): 1 GB is comfortable, 2 GB leaves room. One CPU core is enough for the small project above; the work is waiting on the Bucket and on Postgres, not computing. With Postgres and the bucket on the same machine, plan for more: Scaling and cost has the sizes.

Scaling out. Run several processes against the same Bucket and Postgres, each with one role:

Terminal
sypnia serve --role ingest --listen 0.0.0.0:8081   # as many as you need, behind your load balancer
sypnia serve --role api    --listen 0.0.0.0:8082
sypnia serve --role worker                         # two workers are safe: the ledger decides who does what

With ingest and the worker apart, a segment landing cannot wake the worker directly. The worker finds it in the ledger on its next pass, at most 30 seconds later, which is the case the 2-minute budget in Data flow is computed for.

Cost. The price of the server, plus Postgres and a bucket if they are not on the same machine. The compose.yaml in Deploy with Docker is the production file: the engine, Postgres, an S3-compatible store and HTTPS on one server. The shorter one in the self-host quickstart is for trying it on your own machine.

The pieces you can swap

The engine touches the outside world in four places. Each is a trait in the code and a choice in the documentation. The default deployment uses the smallest option for each.

Figure. The engine's four edges. Everything on the outside of a port can be replaced without touching the inside.
  1. ObjectStore: Amazon S3, Cloudflare R2, SeaweedFS; in tests, a folder.
  2. Database: Postgres on RDS, Supabase, Neon, your own Postgres; in tests, an in-process Postgres.
  3. AiProvider: none by default; OpenRouter, the OpenAI API, the Anthropic API, Google Gemini or any OpenAI-compatible endpoint; in tests, a recorded answer.
  4. AlertSink: the record in Postgres, always, and your webhook.
Read this diagram as text

A hexagon in the centre, the engine, which knows only four traits. Each trait is a port on one side, with its adapters fanned out. A filled dot marks the default deployment: Amazon S3 (or the bucket the template creates), your own Postgres, no AI provider, and the alert record in Postgres. A small cloud marks what Sypnia Cloud uses: Amazon S3, Postgres on RDS and OpenRouter, plus e-mail and in-app alerts, which only Sypnia Cloud has. Dashed boxes are adapters used only in tests. On your webhook you can build your own delivery: e-mail with Amazon SES, or any SMTP.

The two traits not shown on other pages. Notice that every method of the store takes a key built by Keys, never a string, and that a sink receives a finished alert and cannot change it.

crates/sypnia-core/src/ports.rs
/// (1) Where objects live. Implemented over the `object_store` crate for S3-compatible stores,
/// and over a folder for tests and for `sypnia serve` on a laptop.
#[async_trait]
pub trait ObjectStore: Send + Sync {
    async fn put(&self, key: &ObjectKey, body: Bytes, options: PutOptions) -> Result<(), StoreError>;
    /// The object as lines, decompressed as they are read. A segment is never held twice in memory.
    async fn read_lines(&self, key: &ObjectKey) -> Result<LineStream, StoreError>;
    async fn get(&self, key: &ObjectKey) -> Result<Bytes, StoreError>;
    /// Keys under a prefix, in order. `after` continues a listing without re-reading it.
    async fn list(&self, prefix: &KeyPrefix, after: Option<&ObjectKey>) -> Result<Vec<ObjectMeta>, StoreError>;
    async fn delete_prefix(&self, prefix: &KeyPrefix) -> Result<u64, StoreError>;
    /// A link a browser can use directly: to play a replay chunk, or to upload a source map.
    async fn sign(&self, key: &ObjectKey, method: SignedMethod, ttl: Duration) -> Result<Url, StoreError>;
}

/// (4) Where a released alert goes. The engine ships two: the record and the webhook.
#[async_trait]
pub trait AlertSink: Send + Sync {
    fn name(&self) -> &str;
    /// Called once per released alert. An error is retried with growing waits and recorded as a delivery.
    async fn deliver(&self, alert: &ReleasedAlert) -> Result<Delivery, SinkError>;
}

Database (2) is the same idea with more methods: one per statement the engine runs, grouped by table, implemented once with sqlx for Postgres. It is a trait so that tests can count and fail queries, not because another database is on the way. AiProvider (3) is on The agent’s pipeline.

A piece you choose

Object storage

Holds raw events, replay chunks, page snapshots and source maps.

Default deployment
The bucket the template creates, or the one you name in SYPNIA_STORAGE_BUCKET.
Sypnia Cloud uses
Amazon S3.

Your options

A piece you choose

Database

Holds the aggregates, the session index, problems and configuration.

Default deployment
A Postgres URL you provide, or the instance of the database stack.
Sypnia Cloud uses
Postgres.

Your options

A piece you choose

Alert delivery

Gets an alert from the engine to a person.

Default deployment
None. Alerts are recorded, shown in the Console and sent to a webhook if you set one.
Sypnia Cloud uses
E-mail through Amazon SES, and alerts inside the app.

Your options

A piece you choose

AI provider

Runs the model behind the agent’s analysis and the ready prompt.

Default deployment
Off until you set a key.
Sypnia Cloud uses
OpenRouter.

Your options

There is no WhatsApp or Slack sink, in the engine or in Sypnia Cloud. Sending to either is a small receiver of yours on the webhook, and the engine does not need to know.

Which shape to choose

If youChoose
Already run things on AWS and want to pay for use, not for an idle serverAWS functions
Want everything on one machine, or are not on AWSOne process
Want to try the engine on a laptopOne process, with Docker Compose
Expect traffic in burstsAWS functions: more copies appear by themselves
Need your data never to leave your network, including the modelOne process, with an OpenAI-compatible endpoint inside your network

You can change your mind. The Bucket layout and the tables are the same, so moving is pointing the other shape at the same Bucket and the same Postgres.

What changed from the system this comes from

ThereHereWhy
Functions only, deployed with the appFunctions, or one processBrief §10.9: the same binary in both shapes
An ingest function, an hourly function, a daily function, a weekly one, each with its own scheduleThree functions by role; the worker has a queue and one scheduleOne function per role matches --role, and one binary has one configuration
A managed delivery stream between ingest and the bucketA queue on AWS, memory elsewhereFreshness, and objects named by project
x86_64 only, because of a native bindingarm64, or any target Rust builds forNo native dependency left
Five environment variables in the app to send server dataOne ingest key and one URLIts app once reached 3,924 of the 4,096 bytes a function’s environment may hold

Next

  1. One engine, two ways to wake it
  2. As AWS functions
  3. Why a queue, and only one
  4. What the template creates
  5. Cold starts, limits and connections
  6. What it costs on AWS
  7. As one long-running process
  8. The pieces you can swap
  9. Which shape to choose
  10. What changed from the system this comes from
  11. Next

    Search pages, sections and terms