Section 4
Physical architecture and design
How the two services run on AWS: what is deployed where, how traffic and video bytes move, how encoding capacity grows and where it stops, how data is stored, and what all of it costs when nobody is using it. The section ends by following one upload from the owner's browser to playback.
- 4a Key decisions
- 4b Network, nodes, services
- Network
- Compute
- Two encoder lanes
- Launcher and scaling
- Cost
- 4c Persistence
- 4d One upload, end to end
- Questions
4aDecisions that shaped the physical architecture
One rule drives the deployment: pay for work, not for waiting. Everything that can scale to zero does, capacity is bounded by explicit caps instead of open-ended scaling, and video bytes travel between the client and S3 directly instead of through the API.
The platform runs in one AWS account in ap-southeast-1 (Singapore). One CloudFormation stack, generated by a Python program and checked in as a template, describes all of it. Since 18 October one persistent environment, dc2-live, has been running continuously; continuous delivery updates it in place after every green CI run on Main (5 · CD). Before that, each proof run built its own stack and deleted it afterwards, which cost about 25 minutes to deploy and 25–40 minutes to tear down per check.
Each row below is a decision whose effect is visible in that picture. The decision identifiers (AD-xx) are the team's register numbers; the logical decisions behind the two services are on page 3.
| Decision | Why | What it costs |
|---|---|---|
| Every service handler is a Lambda function built from a container image, one image per service (AD-10) | Lambda bills per request and costs nothing idle. One image per service gives Media and Processing separate release units; the existing FastAPI code runs unchanged behind an adapter. | Cold starts, no connection pool (a pooled connection would keep the database awake), a 29 s API Gateway timeout. |
| CloudFront is the single public entry (AD-15) | Managed HTTPS without buying a domain; the static site and /api/* share one origin, so the session cookie can be strict. | The API Gateway URL is still reachable directly, and there is no WAF. |
| No NAT gateway: private subnets get IPv6 egress only, plus a free S3 gateway endpoint (AD-18) | A NAT gateway and paid interface endpoints bill every hour, which would be the largest idle cost of a typical VPC. | Every AWS service the Lambdas use must be reachable over IPv6 or the gateway endpoint; Fargate tasks need public subnets to pull images. |
| Encoders are finite Fargate tasks, started by a launcher, at most 3 (AD-13, AD-27) | FFmpeg needs minutes of CPU; a task that takes one job and exits costs nothing between bursts. | About 26 s of Fargate start-up before each burst; never more than three long encodes at once. |
| Short clips (≤ 60 s, ≤ 64 MiB, ≤ 1080p) are encoded on a Lambda instead (AD-22) | Removes the Fargate start from the wait for the commonest small job, and is cheaper per encode. | Bounded by Lambda's 15-minute limit and the account's 3008 MB memory ceiling; two concurrent encodes. |
| Each service has its own Aurora Serverless v2 cluster that pauses at 0 capacity (AD-12, AD-29) | Relational transactions for leases and the outbox, near-zero idle cost, and no shared database capacity or failure boundary between the services. | The first query after a pause waits several seconds; one instance per cluster, so no failover replica. |
| Clients upload and play straight from S3 with short-lived presigned URLs (AD-14) | API Gateway and Lambda have payload limits and bill for time; 100 MiB uploads would hit both. | The client hashes the file first, and Media must verify the stored object before accepting it. |
| One persistent environment, updated in place, scaling to zero (AD-27) | Replaces a 25-minute deploy and 25–40-minute teardown per check; idle cost is small anyway. | The platform is public all the time, bounded by the throttle, the encoder cap and a budget alert; there is no separate staging environment. |
| One CloudFormation stack, applied in two phases: infrastructure, then applications pinned by image digest (AD-23) | The smallest operational surface for three people. | Infrastructure for both services changes together; only code releases are independent (5 · CD). |
4bNetwork, nodes, technologies and cloud services
Requests enter through CloudFront and API Gateway and run on Lambda functions inside private subnets. Background work flows through SQS queues. Encoding runs either on a bounded Lambda or on finite Fargate tasks that a launcher starts from the backlog. Every one of these stops costing compute when there is no work.
Network: VPC, subnets, endpoints and egress
One VPC (10.62.0.0/16 plus an Amazon-provided IPv6 block) spans two Availability Zones, with one private and one public subnet in each.
| Place | What runs there | How it reaches other things | What can reach it |
|---|---|---|---|
| Private subnets | All 11 Lambda functions (attached to the VPC) and both Aurora clusters | No IPv4 default route and no NAT. An IPv6 route through an egress-only internet gateway reaches the dual-stack endpoints of SQS, SSM and ECS. An S3 gateway endpoint, restricted by policy to the source and output buckets (and the regional ECR layer bucket), carries S3 traffic. | Nothing from the internet. The database security group admits port 5432 only from the Lambda, worker and migration security groups. |
| Public subnets | Fargate encoder tasks, plus the one-off migration and bootstrap tasks | A temporary public IPv4 address while the task runs, used to pull the image from ECR and to reach SQS and S3. | Nothing: the task's security group has no inbound rule, and the container listens on no port. |
| Outside the VPC | CloudFront, API Gateway, S3, SQS, EventBridge, SSM, ECR, CloudWatch | Regional or global managed services | Public edge: ports 80 and 443 only; 80 redirects to HTTPS. Buckets and queues: resource policies, TLS only. |
An external scan of the public surface found only ports 80 and 443 open, and Aurora reports PubliclyAccessible=false s229.
Avoiding NAT keeps the idle bill near zero, but it ties the design to services that answer over IPv6 or through the S3 gateway endpoint, and it forces the encoders onto public subnets. A public subnet here means the task can open connections out; it has no listener and no inbound rule. The end-to-end smoke test proves the paths it uses work; no test checks each network route individually.
The API Gateway execute-api URL is reachable directly, not only through CloudFront, and there is no WAF, GuardDuty or intrusion detection. The protections on that path are the authorizer, the stage throttle (20 requests/s, burst 50), the budget alert and the per-service error alarms. The planned fix is a secret origin header that only CloudFront sends, checked by the authorizer, plus AWS WAF managed rules.
Compute: API Gateway, the authorizer and the Lambda functions
The public path. CloudFront serves the static web app from a private S3 bucket (origin access control, content-hashed file names, cached at the edge) and forwards /api/* to API Gateway with caching disabled, because API responses are per-owner and short-lived. API Gateway is an HTTP API with two route groups, /api/media/* to MediaApi and /api/processing/* to ProcessingApi, and one stage throttle of 20 requests/s with a burst of 50.
The authorizer. Every route except health, register, login and logout first calls MediaAuthorizer, a Lambda built from the Media image. It verifies the session cookie (an HS256 JWT), re-reads the current user row from media_db so a role change or deleted account takes effect at once, and hands API Gateway an owner ID and role. The services trust only that context and strip any identity header a caller sends. Who may do what is explained in 3 · Access.
The functions. Media and Processing are the two services. Each is one container image; the image runs as several Lambda functions, and ImageConfig.Command picks which handler each function starts. A function is a deployment unit of its service, not a separate microservice. Every function has a live alias, and releases move that alias (5 · CD).
| Function (image) | Comes in | What it does and changes | Goes out |
|---|---|---|---|
| MediaApi (Media, 2048 MB) | Owner HTTP requests with the authorizer's owner ID | Accounts, upload reservations and finalize, asset list and status, playback links, retry, edit, delete. Writes media_db; stages commands in Media's outbox in the same transaction. | JSON responses; presigned S3 URLs |
| MediaAuthorizer (Media, 512 MB) | Cookie of every protected request | Verifies the JWT, reads the user row | Allow/deny plus owner ID and role |
| MediaRepair (Media) | EventBridge tick every minute | Publishes due outbox rows; retires expired reservations; deletes sources and outputs of deleted assets | Commands on the commands queue |
| MediaResults (Media) | Messages on the results queue (at most 2 concurrent) | Records the message in Media's inbox and updates the local projection of the job (3 · Projection) | Nothing; status reads use the projection |
| ProcessingApi (Processing, 2048 MB) | Owner and operator HTTP requests | Owner-filtered job reads (one job, or a batch by asset ID), retry and delete | JSON responses |
| ProcessingCommands (Processing) | Messages on the commands queue (at most 2 concurrent) | Inbox, then creates or updates the Job and Attempt; stages work and result messages; publishes them straight away | Work on a work queue; results; a launcher wake |
| ProcessingRepair, EcsEvents, S3Events (Processing) | Minute tick; ECS task-stopped events; S3 object-created events on the output bucket | One repair pass: publishes due outbox rows, expires dead leases, re-sends lost work, cleans up. The two event functions run the same pass early. | Results and re-sent work |
| ProcessingLauncher (Processing, 512 MB) | An asynchronous wake after each standard work send; a minute tick as a safety net | Decides how many encoder tasks to start (below) | ECS RunTask calls |
| ProcessingShortEncoder (worker image, 3008 MB) | One message from the short-work queue | Claims the attempt and encodes it, the same code the Fargate task runs (below) | Outputs in S3; the attempt's result staged in SQL |
Lambdas open a fresh database session per invocation and close it at the end (SQLAlchemy NullPool). A warm pool would keep Aurora from pausing. Configuration comes from SSM Parameter Store SecureStrings read at cold start; each function's IAM role can read only its own service's parameters, and each function has its own least-privilege role (ProcessingApi has no S3 or SQS access; MediaApi has no SQS access).
Both were measured with a load generator running as a Fargate task in the same region r1017b, so they exclude internet latency to real users. The status route reads Media's own projection in one owner-filtered query, which is why it stays fast: no status request calls Processing.
The account's Lambda concurrency limit was 10 when the system was designed; it was 1000 when read on 21 October. Under the old limit, background consumers (two queue consumers at 2 each, repair ticks, launcher, short encoder) could take 9 of the 10 slots. The caps were kept as designed rather than re-tuned to the new limit.
Two encoder lanes: a Lambda for short clips, Fargate for the rest
Processing has one encode pipeline (download the pinned source, check its hash, probe, write an MP4 and an HLS ladder at 360/480/720p capped at the source height, record the outputs) and two places to run it.
Short lane: ProcessingShortEncoder Lambda | Standard lane: Fargate task | |
|---|---|---|
| Takes | Sources at or under all three bounds: 60 s duration, 64 MiB size, 1080 px height | Everything else, including any job that has already tried the Lambda |
| Fed by | short-work queue; an event source mapping delivers one message per invocation | work queue; a task started by the launcher polls it |
| Size | 3008 MB memory (about 1.7 vCPU), 2 GiB /tmp, 900 s timeout, 720 s pipeline deadline | 2 vCPU, 4 GiB, lifetime up to 1800 s |
| Concurrency | At most 2 (MaximumConcurrency on the mapping) | At most 3 tasks |
| Start-up | None when warm; a cold start added about 2.6 s | Median 25.6 s from task created to started (12 tasks) |
| Image | The same worker image in both lanes; the Lambda overrides the entry point | |
How a job is routed. The facts needed arrive at two different times, so routing happens in two stages.
- At dispatch, when Processing stages the work message, only the source's size is known (Media does not probe the video). A source over 64 MiB goes to the standard queue; anything smaller goes to
short-work. A job that has any earlier attempt bound to a Lambda (task name startinglambda-) also goes to the standard queue, so a job that crashed, timed out or was redirected on Lambda is never sent back there. - At the executor, the Lambda claims the attempt, downloads the source and probes it. If the clip is longer than 60 s or taller than 1080 px, it does not encode. It performs the same fenced transition a retry uses: the old attempt becomes abandoned, a new attempt with the next number is queued on the standard lane, and the job goes back to
queued. The owner sees one job; the wasted download and probe add to that job's latency.
Both lanes claim with the same SQL, hold the same lease and commit with the same fence, so a duplicate message, a late invocation or a worker from an older attempt cannot write a second result (3 · Lease). If a Lambda times out mid-encode, its lease stops being renewed; recovery marks the attempt abandoned and the job failed, and the owner's retry goes to Fargate because of the lambda- binding. If the short queue's URL is missing from a function's configuration, dispatch falls back to the standard queue, so a half-configured stack degrades to Fargate instead of losing work.
Why a queue and not a direct invoke. A queue gives redelivery, a dead-letter queue and the same work message the Fargate worker reads, so the attempt fencing needs no new code. The short queue's visibility timeout is 960 s, longer than the 900 s function timeout, as SQS requires.
Measured on dc2-live, 21 October sl1021: five jobs per lane of one 24 s 640×360 clip. To force the Fargate lane on the same stack, the Fargate copy had 70 MiB of padding appended (75.9 MB, identical audio and video streams).
The lane does what it was built for: it removes the Fargate start from the queue wait and costs about a seventh as much per short encode. It does not make the whole job fast. Queue wait plus encode is under 6 s on a warm Lambda, yet submit-to-done is 38–88 s; 35–80 s of every job, on both lanes, is spent outside the queue and the encoder. 4d shows where that time sits in the flow.
One run, one clip, five jobs per lane. The lane's own keep rule required the cold Lambda job to beat the Fargate median; it did not (92.0 s, one sample, against 87.7 s), probably because the first job after an idle spell also waited for Aurora to resume. The lane stays enabled on dc2-live on the strength of the queue-wait and cost results; turning it off is one constant in the deploy code, and the next deployment removes the queue, function and mapping.
Lambda gives up Fargate's 2 vCPU: the account refused more than 3008 MB of memory (about 1.7 vCPU) when the lane was first deployed, so a Lambda encode is expected to run about 15 % longer per second of video. In exchange it starts in under 3 s instead of about 26 s, and a short encode costs a seventh as much.
The launcher: how encoding capacity scales, and where it stops
There is no ECS service and no auto-scaling policy. ECS service auto-scaling keeps a desired number of long-running tasks and adjusts it from a metric; it needs at least one task running to react quickly, which is the idle cost this design avoids. Instead, a Lambda called the launcher starts finite tasks, each of which takes one attempt and exits.
| Comes in | What it does | What changes | Goes out |
|---|---|---|---|
An asynchronous wake from any function that has just sent a message to the standard work queue; a one-minute EventBridge tick as the safety net | Reads three facts: queued attempts in processing_db (the durable truth), visible messages on the work queue (proof a worker could receive something), and every worker task ECS reports. Demand is the smaller of the first two. It starts min(demand − workers not yet holding an attempt, 3 − occupied slots). | Inside one transaction holding the single launcher_control row, it inserts one launch_reservations row per task, with a client token and the full RunTask payload, and commits before calling ECS. | RunTask per reservation, replayed with the identical token if the reply was lost |
Why the reservation rows. Two wakes can arrive together, and an ECS reply can be lost. Because reservations commit first under a row lock, concurrent launchers queue behind each other and each sees the slots already taken. A reservation that ECS has not confirmed still occupies a slot. If no task appears, the launcher finds it by its startedBy tag or replays the same token after 15 s; after 120 s an unconfirmed reservation is released, and a task that turns up later is still counted from the live ECS inventory. The cap of 3 therefore holds under concurrent wakes, lost replies and a killed launcher.
The task's side. A Fargate task receives one work message, claims that attempt in SQL (binding its task name to the attempt), encodes, commits the result under its lease, deletes the message, and exits after two empty 20 s polls. A task that stops without ever claiming anything pauses launches for 120 s; three in a row stop the launcher until it is re-enabled, so a broken image cannot loop through paid starts.
Where scaling stops.
- Encoders: at most 3 Fargate tasks plus 2 short-lane Lambdas, so at most 5 encodes at once. Three is a cost and database-connection choice; the account's Fargate quota (30 vCPU when last read) would allow more.
- API: the stage throttle of 20 requests/s, burst 50; then Lambda account concurrency.
- Databases: each Aurora cluster scales from 0 to 2 ACU and no further.
- Spend: an AWS Budget of USD 20/month alerts at 50, 80 and 100 %; it does not stop anything.
Work beyond the cap waits in the queue and in SQL; nothing is dropped.
Measured. On dc2-live, three concurrent 20 s clips took the encoder count from 0 to 3 and back to 0, and a nine-clip backlog at the cap finished in 239 s (2.26 jobs/min) v2live-0919. The scaling ratio was measured earlier, on V1 stacks where an operator started a batch of 1, 2 or 3 tasks of the same size, with a six-clip backlog and one run per worker count r1018b:
The two-worker miss is on six clips with one run per count; Fargate task-time variability against a fast one-worker baseline is the likely cause, but no per-task CPU profile was captured to confirm it. The standard-lane queue wait is the price of having no idle encoder: each burst pays a Fargate start (median 25.6 s over 12 tasks) plus the image pull. The short lane removes that price for small clips.
Three concurrent long encodes is the ceiling, and work arriving while all three are busy waits for one to exit. The ratios come from six clips and one run per worker count; the proposal's 30-clip comparison was not repeated on AWS. Recovery of a lost queue entry within 120 s was asserted only on a simulated clock locally, not measured on AWS.
A warm pool of one encoder would remove most of the 37 s wait for long clips, at about USD 0.13 per hour of idle task (about USD 94 a month if always on). The team chose zero idle cost and the short lane instead.
Cost model: pay for work, not for waiting
Every component falls into one of two groups: things that bill while idle, and things that bill only per request, per second of compute or per GB stored.
| Component | Idle cost | Cost while working (Singapore rates used by the team's model) |
|---|---|---|
| Lambda functions | 0 | USD 0.0000166667 per GB-second plus requests; a short encode costs about USD 0.0003 |
| Fargate encoders | 0 (no task runs) | About USD 0.128 per task-hour including the public IPv4 address, 60 s minimum; a padded 24 s clip cost about USD 0.0021 |
| Aurora (two clusters) | Storage and the managed master secret: about USD 0.51 a month per cluster; compute 0 while paused | USD 0.20 per ACU-hour per awake cluster; a cluster pauses after 300 s without connections |
| API Gateway, SQS, S3, CloudFront | S3 storage only | Per request and per GB; USD 1.25 per million API requests |
| Logs, alarms, ECR, parameters | Small fixed amounts | Logs are kept 7 days |
| Deliberately absent | NAT gateway, paid interface endpoints, load balancer, always-on encoder, message broker: each would bill every hour whether or not anyone uploads | |
The team's model puts the idle environment at about USD 3–5 a month, set when there was one database cluster; the second cluster adds about USD 0.51 a month while paused. A burst of work adds Aurora time at USD 0.20 per ACU-hour for each cluster that wakes, plus the encode itself cost-model.
Two details keep the databases paused when nobody is using the platform. Lambdas hold no open connections, and the minute repair ticks do not query SQL while an SSM "quiet" marker says nothing is due; a writer (the command consumer or an API) clears that marker. Aurora was observed at 0.0 ACU about 56 minutes after the last upload lv12.
The USD 3–5 figure is a model, not a bill: Cost Explorer showed USD 0.00 with credits applied, and the October bill had not been read when this was written. The 0 ACU observation is one point in time, before the database split. The budget alerts; it does not cap spend. The quiet markers are best effort: a lost marker write can delay a repair by up to 30 minutes, after which every tick runs a full SQL pass.
4cPersistence design
Each service owns its own PostgreSQL database on its own Aurora cluster, reached only with that service's credentials. S3 holds every video byte, under versioning, so a source can be pinned to one immutable version. SQS carries messages between the services. No table, credential or cluster is shared.
| Store | Owner | Holds | Rules that keep it correct |
|---|---|---|---|
Aurora cluster with media_db | Media | Users, assets, upload reservations, pinned source versions, idempotency keys, the projection of Processing's results, cleanup state, outbox and inbox | Every query is filtered by owner; a pinned source cannot change after finalize; the asset and its submit command commit together |
Aurora cluster with processing_db | Processing | Jobs, attempts, submission guards, retry requests, task-to-attempt bindings, launcher reservations, cleanup state, outbox and inbox | One job per asset; leases checked on the database clock; only the current attempt with a live lease can finish |
| S3 source bucket | Media (Processing reads) | Uploaded videos at staging/{owner}/{reservation}/source, or sources/{owner}/{asset}/source for edits | Versioned; the asset records the exact VersionId, size and SHA-256 that were verified |
| S3 output bucket | Processing writes, Media serves | jobs/{job}/attempts/{n}/primary.mp4 and …/hls/ | Exactly one primary output; outputs are scoped to the attempt, so a stale attempt cannot overwrite the current one |
SQS: commands, work, short-work, results | Producer and consumer roles listed in each queue's policy | JSON messages with identifiers and state; never bytes, URLs or credentials | Standard queues: at-least-once and unordered, so consumers deduplicate |
Why the boundary sits here, and the Asset, Job and Attempt states, are on page 3: contexts, Asset, Job and Attempt, source pin.
Aurora configuration
Both clusters run Aurora PostgreSQL 16 Serverless v2 with one instance each, 0 to 2 ACU (one ACU is about 2 GiB of memory with matching CPU), auto-pause after 300 s without connections, storage encryption, forced TLS (rds.force_ssl=1, verified CA), one-day automated backups, deletion protection, and a Retain policy so deleting the stack keeps the data. Each database has three roles, created by a one-off bootstrap task:
*_ownerowns the schema and cannot log in;*_migratorinherits the owner and runs that service's Alembic migrations (Media and Processing have separate histories);*_runtimemay only select, insert, update and delete.
Each runtime login is stored as an SSM SecureString that only that service's functions can read. On AWS, a Media login to processing_db was refused, and a schema change attempted as a runtime role was refused s229.
Why two clusters
Until 21 October both databases sat on one cluster: separate roles and migrations, but one instance, one capacity ceiling and one failure boundary. Load or a fault in one service's database could slow or stop the other. The split gave each service its own cluster without replacing live data:
- check that Processing is idle, then take a manual snapshot of the shared cluster;
- a stack update creates
processing_db's new cluster as a copy-on-write clone of the shared one (Media keeps the original); - reset Processing's logins on the clone, freeze the old copies, and point Processing's connection parameters at the clone;
- run the public smoke test; only after it passes does each cluster drop its copy of the other service's database.
It was rehearsed on a throwaway stack, then applied to dc2-live by the CD pipeline on 21 October; the pre-split snapshot is kept 39644028238.
The split costs a second cluster's storage and secret (about USD 0.51 a month) and a second wake-up: each cluster pauses and resumes on its own. In return a Processing backlog no longer consumes Media's database capacity. The extra wake surfaced immediately: on 22 October three deployments failed because their smoke test woke Media's cluster with a login but then met Processing's cluster still asleep (5c).
Each cluster is one instance in one region, with no replica, so a database or zone failure stops that service until Aurora recovers it. Backups are kept one day, and no restore drill was run. Every protected Processing API call still passes Media's authorizer, which reads media_db, so the public Processing API depends on Media's cluster; background encoding does not.
Aurora wake behaviour
A paused cluster resumes when a connection arrives. The first query waits for that.
A user who arrives after a quiet spell can therefore see one slow request or a 503 that succeeds on retry. The deploy smoke test retries exactly that case (5 · CD). The 4.7 s and 263 ms figures come from r1017b; the 503 from 39542434067.
Tables
The rows that make the hand-off between services safe (outbox, inbox, lease columns, projection version) are explained on page 3: outbox and inbox, idempotency, lease, projection.
S3 and SQS settings
S3. Three buckets (source, output, frontend), all versioned, encrypted with SSE-S3, public access blocked, and a bucket policy that refuses non-TLS requests. Uploads use a presigned POST whose policy fixes the key, the content type and a length range up to 100 MiB, valid for 15 minutes. Playback uses presigned GET links valid for 900 s, issued only after an owner check; HLS segments are served by a 307 redirect to a fresh signature. CORS allows only the frontend's origin. Because buckets are versioned, deleting an asset deletes every version of its source and outputs, asynchronously after a tombstone.
SQS. Four standard queues, each with a dead-letter queue: messages are kept 7 days (dead-letter queues 14 days), the visibility timeout is 420 s (960 s on short-work), and a message moves to its dead-letter queue after 5 failed receives. Queue resource policies deny SendMessage to every role except the listed producers, and receive and delete to every role except the listed consumers; a direct send by another principal was refused on AWS. FIFO queues would give ordering and deduplication, but at lower throughput and with message-group design; the inbox and version checks already tolerate duplicates and reordering, so standard queues are enough.
What is kept, and for how long
| Data | Kept |
|---|---|
| Session cookie (JWT) | 1 hour; not stored on the server |
| Upload grant / playback link | 15 minutes / 900 s |
| Accounts, assets, sources and outputs | Until the owner deletes the asset (accounts until the environment is torn down); no age-based expiry |
| Jobs, attempts, outbox and inbox rows | Until the environment is torn down; no pruning job |
| SQS messages | 7 days; dead-letter queues 14 days |
| Logs | 7 days |
| Aurora backups | 1 day automated; the pre-split snapshot and a final snapshot at teardown are kept |
Data is classified in four levels: restricted (password hashes, keys, the JWT secret: SSM SecureStrings and bcrypt at cost 10), confidential (accounts, owners' videos, original file names), internal (job and message metadata) and public (the static web app).
4dOne upload, from bytes to playback
An owner uploads a video and plays the encoded result. The request path only reserves, verifies and reads; the bytes go straight to S3; every hand-off between services is a committed database row followed by a queue message; and the encoder that does the work can only record a result while it holds the attempt's lease.
This use case touches every node in the deployment: the edge, both services and their databases, S3, every queue, the launcher and an encoder. The diagram follows a short clip; the standard-lane difference is noted at step ⑤.
Step by step
| Step | What happens | What changes | What it protects |
|---|---|---|---|
| ① Reserve | The client hashes the file and sends its name, type, size and SHA-256. MediaApi checks the type list and the 100 MiB cap. | An UploadReservation row keyed by owner and request ID; a presigned POST that fixes the key, type and length | A repeated reserve with the same request ID returns the same grant; a changed body gets 409 |
| ② Upload | The client posts the bytes to the source bucket. No cookie and no API call is involved. | A new object version in S3 | S3 refuses anything over the length range (100 MiB + 1 byte was refused with 400) |
| ③ Finalize | MediaApi reads the stored object at an explicit VersionId, outside any row lock, and checks size, SHA-256 and the video file signature. Then one transaction pins that version, creates the Asset and stages a submit message in Media's outbox. | Asset row, pinned source version, outbox row; 202 to the client | The bytes that were verified are the bytes that will be encoded; a missing object returns 409 and nothing is adopted. See source pin. |
| ④ Publish | MediaRepair, on its minute tick, claims due outbox rows with SKIP LOCKED, sends them to the commands queue and marks them sent under its claim token. | Outbox row marked sent | A committed command is never lost; a lost reply can resend the same message ID (outbox) |
| Accept | ProcessingCommands records the message in its inbox, locks the asset's submission guard, creates the Job and Attempt 1 as queued, and stages a work message and a queued result. It publishes both at once. | Job, Attempt, inbox and outbox rows | One job per asset; a duplicate submit is a no-op (idempotency) |
| ⑤ Launch | The work message goes to short-work if the source is 64 MiB or less, otherwise to work. The short-lane Lambda is triggered directly; for the standard queue, the send wakes the launcher, which reserves a slot and starts a Fargate task. | Launch reservation (standard lane) | The cap of 3 tasks (launcher) |
| Claim and encode | The encoder claims the current attempt, binds its task name, takes a lease on the database clock and stages a processing result. It downloads the pinned version, checks the hash, probes, writes the MP4 and the HLS ladder (never above the source height). | Attempt processing; outputs under the attempt's own prefix | A lease is required; a short-lane probe over 60 s or 1080 px redirects the job to Fargate (lanes). If HLS fails, the MP4 is kept. |
| Finish | Under the live lease, the encoder records exactly one primary output plus optional HLS, sets done and stages the done result; only then does it delete its queue message. The encoder cannot send messages. | Job done; outbox row | A worker whose lease expired, or from an older attempt, cannot finish (lease) |
| ⑥ Project | A Processing repair pass publishes the result. MediaResults deduplicates it in Media's inbox and updates the projection only if its version is newer for the same job, source and attempt. | Projection row | Never moves backwards; conflicting content at the same version is rejected (projection) |
| ⑦⑧ Play | The client's 2 s poll reads Media's projection. On done it gets a presigned MP4 URL and an HLS playlist route; each segment request is redirected (307) to a fresh signed S3 URL. | Nothing | Owner only (a foreign ID gets 404); responses are private, no-store |
Where the time goes
The benchmark recorded only the attempt's queued, started and finished times, so it could not say where the rest went. The sequence above shows two waits that lie outside those stamps: the submit command leaves Media's outbox on the next MediaRepair tick (up to 60 s, 30 s on average), and the done result leaves Processing's outbox on the next repair pass, which is the minute tick unless an ECS-stopped or S3 event triggers it earlier. Together with the client's 2 s poll and an Aurora resume after an idle spell, those are a plausible account of the 35–80 s per job. This is a reading of the code, not a measurement; the planned next step is per-stage timestamps.
Publishing from the minute tick keeps request handlers short and makes the outbox the only path for messages, so a crash between commit and send cannot lose a command. Publishing immediately after commit (as ProcessingCommands already does) and keeping the tick only as the safety net would remove most of that wait at no cost in safety.
What the same flow does when something goes wrong
- The upload never arrived, or the bytes differ from the reservation: finalize adopts nothing and answers 409 (no object), 422 (size or hash differs) or 415 (not a video of the declared type); the reservation expires and is cleaned up.
- A message is delivered twice: each consumer's inbox turns the second delivery into a no-op; 18 sends for 9 jobs were observed on AWS and all 9 jobs finished once lv11.
- An encoder dies mid-encode: the stop was detected in 5.8 s on AWS (target 300 s); the attempt becomes abandoned and the job
failed. The owner's retry creates attempt 2 from the stored source, with no new upload. - Processing is down: Media keeps accepting uploads, because it only commits to its own outbox. With the command consumer switched off for 48 s, Media answered 202, and the job was done 58.9 s after the consumer came back.
- A result arrives late or out of order: the projection ignores older versions and rejects conflicting ones.
Questions a professor may ask
Why run short clips on Lambda and long ones on Fargate, instead of picking one?
Lambda starts in seconds but is limited to 15 minutes per invocation, 10 GB of temporary storage and, in this account, 3008 MB of memory (about 1.7 vCPU). Fargate has no such limits but takes about 26 s to start a task. All-Lambda would fail on long or large sources, or require splitting encodes into segments, which is a different pipeline. All-Fargate means every job, including a 10 s phone clip, waits for a task to start unless an encoder is kept warm, which costs about USD 0.13 per idle hour. Two lanes give each job the cheaper fast path when it fits and keep a general path for the rest. Both lanes run the same image and the same leased pipeline, so the second lane added routing, not a second implementation. The cost is a second queue, a sticky fallback rule, and one wasted download when a small file turns out to be too long.
Why a custom launcher rather than ECS service auto-scaling or AWS Batch?
An ECS service keeps a desired count of long-running tasks and adjusts it from a metric. To react without a cold start it needs at least one running task, and scaling to zero from a queue metric reacts in minutes. The work here is naturally finite (one attempt per task), so starting a task per job and letting it exit fits better. AWS Batch does that too but adds compute environments and job queues as another dependency, and still pays a container start. The launcher is a small Lambda: it compares SQL backlog, queue depth and running tasks and starts the difference up to a cap. Its risk is the classic one for custom schedulers, launching too many; that is handled by committing a reservation row under a single-row lock before every RunTask and replaying the same client token after a lost reply. It was tested with concurrent wakes and lost replies against real PostgreSQL and observed going 0 → 3 → 0 on AWS. Its limits: a hard cap of 3 and no scaling on CPU or latency.
Why two Aurora clusters? Is that not more expensive, and is it highly available?
Separate databases and roles already prevented one service from reading the other's tables. They did not separate capacity or failure: on one cluster, a Processing backlog consumed the ACUs Media needed for logins and status, and a failure of that instance stopped both. A cluster per service removes that shared boundary. The cost is small because both pause at 0 ACU: about USD 0.51 a month of storage and secret while idle, plus a second cluster's ACU-hours when both are busy. The real cost turned out to be operational: each cluster wakes separately, and three deployments failed until the smoke test retried the first Processing call as well as the login. It is not highly available. Each cluster has one instance in one region and no replica; adding a reader in a second zone would give failover but would also bill for an instance that never pauses. Zone and region failover were out of scope.
Why no NAT gateway, and why are the encoders on public subnets? Is that safe?
A NAT gateway bills every hour plus per GB, and interface endpoints bill per hour per zone; on a platform idle most of the day that would be the largest line on the bill. Instead the private subnets have IPv6 egress through an egress-only gateway (free) and an S3 gateway endpoint (free); SQS, SSM and ECS answer on dual-stack endpoints. Fargate tasks need to pull images from ECR and reach SQS, which in this layout means a public IPv4 address, so they run in public subnets. That is safe in the sense that matters: their security group has no inbound rule and the container listens on nothing, so the address can only originate connections. The database is still private and admits only the Lambda, worker and migration groups. The cost of the choice is a dependency on IPv6 support for every service the Lambdas call, and the hourly public IPv4 charge while a task runs (included in the USD 0.128 task-hour).
What does the platform cost when nobody uses it, and what stops a runaway bill?
The model gives about USD 3–5 a month idle (logs, alarms, the database secrets, image storage and S3 storage), plus about USD 0.51 a month for the second database cluster. Compute is zero idle: Lambda bills per request, no encoder runs, and both clusters pause after 300 s without connections. The bill grows only with work: Aurora at USD 0.20 per ACU-hour while awake, Fargate at about USD 0.128 per task-hour, Lambda per GB-second. Spend is bounded by the stage throttle (20 requests/s), the encoder caps (3 Fargate plus 2 Lambda) and the 2 ACU ceiling per cluster, so the worst case per hour is known. The AWS Budget at USD 20 a month alerts at 50, 80 and 100 %, but it does not stop anything; an operator kill switch closes intake and stops launches. The actual bill has not been read yet: Cost Explorer showed USD 0.00 with credits applied.
Why Aurora PostgreSQL rather than DynamoDB, which scales to zero without a wake-up delay?
The correctness rules depend on SQL transactions: state and outbox row committed together, outbox claims with FOR UPDATE SKIP LOCKED, a submission guard locked before the job and attempt, leases compared with the database's own clock, and a deferrable foreign key so a job and its first attempt insert together. DynamoDB has transactions, but each of those patterns would need redesigning around conditional writes and item-level versioning, and the inherited code was already SQLAlchemy and Alembic. Aurora Serverless v2 keeps that model and still pauses at 0 ACU. The trade-off is the resume delay (4.7 s for the first read) and VPC attachment for every function. DynamoDB and the RDS Data API (which would remove VPC attachment) are on the backlog, each needing a compatibility spike.
Submit-to-done is 45 s even on the fast lane. Where does the time go, and how would you fix it?
On a warm Lambda job, queue wait plus encode is under 6 s, so roughly 40 s is elsewhere. The measurement only stamped queued, started and finished, so it cannot attribute the rest. The code shows two hand-offs that wait for a scheduled pass: Media's submit command is published by the one-minute MediaRepair tick, and the final result by the next Processing repair pass. Each adds up to 60 s, about 30 s on average, which fits the 35–80 s observed. The fix is to publish immediately after the commit in the request or encoder path and keep the tick as the safety net, as ProcessingCommands already does; it changes latency, not safety, because the outbox row is still committed first. The first step, though, is per-stage timestamps, so the fix is confirmed rather than assumed. The 20 s end-to-end aim stays unmet until then.
What does a user see if the database has paused?
The first request that needs a paused cluster waits while Aurora resumes. A read after a pause took 4.7 s on AWS. If the resume takes longer than Media's connection timeout (about 10 s), the API answers 503 and the next try succeeds. Health checks do not touch the database, so they stay fast. The alternative is a minimum capacity of 0.5 ACU, which never pauses and costs about USD 0.10 per hour per cluster, about USD 73 a month each. For a demonstration platform the team chose the pause; the deploy smoke test retries only that case (502/503/504 on the first database call, three times, within 180 s) so a pause cannot fail a deployment.