Section 3
Logical architecture and design
FlickPond is two services. Media decides who owns what and who may see it; Processing decides how a video gets encoded. They share no database and never call each other: they exchange messages through queues, and a small set of mechanisms keeps them consistent when messages are late, duplicated or lost.
- 3a Key decisions
- 3b Components
- 3c Domain model
- Contexts
- Asset, Job, Attempt
- Source pin
- Outbox and inbox
- Duplicates
- Lease
- Projection
- Access
- Producers and consumers
- Questions
3aDecisions that shaped the logical design
One decision drives the rest: split the system where the rules change, between owning a video and encoding it, and let the two halves communicate only through messages. Each decision below follows from that, and each has a price.
The requirement from section 1 is a reusable workflow (upload, process, status, playback) whose encoding capacity can grow and shrink without touching the user-facing API. The proposal drew a design for that with a synchronous call from Media to Processing, a Redis job queue and a shared service token. Moving to managed AWS services changed three of those choices, and the lecturer asked the team to confirm the service split with a detailed domain analysis. The decisions as built:
| Decision | What it does | Why | What it costs |
|---|---|---|---|
| Two business services (AD-01) | Processing is extracted as the only new service. Accounts, ownership, upload intake and playback stay together in Media. | Processing has its own rules (attempts, leases), lifecycle and CPU-heavy scaling. Every playback or retry decision needs owner and Asset together, so splitting identity or playback out would turn single-database joins into calls between services. | More integration work than a single application. Contexts |
| A database per service (AD-02, AD-29) | media_db and processing_db, separate migration histories, separate login roles; since 21 October each on its own Aurora cluster. | Ownership is enforced by the database, not by convention: neither service's login can open the other's database. | No join or transaction across the two; consistency must come from messages. A second cluster to pay for. 4c |
| Queues with an outbox and inbox (AD-11) | State changes and the messages they cause commit together in SQL; SQS carries them; the receiver records each message before acting on it. | Media keeps accepting uploads while Processing is down; no always-on broker such as Redis. | Delivery is at least once, so duplicates are normal and every receiver must tolerate them. Repair is part of the design. Outbox |
| Direct-to-S3 upload with a pinned version (AD-14) | The client uploads straight to storage under a short grant; Media then verifies the bytes and pins that exact S3 object version. | No 100 MiB body passes through the API, and the bytes that were checked are exactly the bytes that get encoded. | A two-step protocol; the client must hash the file first. Source pin |
| Media keeps a projection (AD-21) | Media stores its own copy of each job's state, updated from Processing's result messages. | Status and playback never wait on Processing. | The copy can be briefly behind. Projection |
| Identity checked once, at the gateway (AD-09, AD-20) | A Media-owned authorizer turns the session cookie into a trusted owner identity for both services; IAM restricts who may send to or read from each queue. | Processing trusts the owner without holding Media's secret or user table. | One database read per request; Processing's public routes depend on Media's authorizer. Access |
| A versioned published contract (AD-24) | One message envelope and two OpenAPI documents; consumers accept the current and previous version and ignore unknown fields. | Additive changes can ship in either service first. | The contract code is copied into both images (a shared kernel), so a breaking change takes two releases. Contract |
Three proposal decisions were replaced: the synchronous SubmitJob call became an asynchronous submit message, because a direct call makes Media's availability depend on Processing's; Redis/RQ became SQS, because Redis needs a server running all the time; and the shared service token became the gateway-trusted identity plus IAM, because serverless functions have no private network for a token to protect. AD register
3bLogical components
Each service is several small functions sharing one codebase, one image and one database. The functions are deployment units, not extra services: a service is something with its own data, rules and release.
Logical deployment view
What each component receives, does and hands on
| Component | Comes in | What it does and changes | Goes out |
|---|---|---|---|
| Media authorizer | Every request to a protected route, with its session cookie | Verifies the signed cookie and reads the current user row (deleted user or changed role takes effect at once). Changes nothing. | Allow, plus the trusted owner ID and role; or deny (401) |
| MediaApi | Owner requests: register, log in, reserve upload, finalize, list and read jobs, retry, edit, delete, HLS playlist | Checks ownership on every Asset; creates upload grants; verifies uploads and creates Assets; stages commands in the outbox; signs playback links | HTTP responses; submit/retry/cancel rows in Media's outbox (sent later by MediaRepair) |
| MediaResults | Result messages from media-results | Records the message in Media's inbox and updates the projection in one commit, applying only newer, valid states | Deletion of the message from the queue, only after the commit |
| MediaRepair | A tick every minute | Sends due outbox rows; expires unused upload grants; deletes a deleted Asset's source once Processing has confirmed the cancel | Commands on processing-commands |
| ProcessingCommands | Commands from processing-commands | In one commit: inbox row, submission guard, Job and Attempt (or a new Attempt for retry, or cancellation), and outgoing result and work rows | Sends its outbox straight after the commit: a result to Media, a work message to an encoder queue |
| Repair and event handlers | A tick every minute; ECS "task stopped" and S3 "object created" events as hints | Sends due outbox rows (this is how encoder results leave); marks Attempts with an expired lease as abandoned; re-sends work lost from a queue; cleans up outputs of dead Attempts | Results and repeated work messages |
| Launcher | A wake-up on every work send, plus a one-minute safety tick | Counts queued Attempts in SQL and reserves launch slots, never more than three running; starts Fargate tasks | ECS task starts |
| Encoders | A work message for one Attempt | Claims the Attempt (gets a lease), downloads and checks the pinned source, runs FFmpeg, uploads outputs, records the finish under a live lease | Files in S3 and rows in processing_db; never a queue message |
Memory sizes, network placement and the two encoder lanes are physical concerns: 4 · Compute, 4 · Lanes, 4 · Launcher.
Layers inside each service
Both services follow the same layering. The API layer (FastAPI routes) receives a request with an already-trusted owner identity, validates the input and calls the domain layer. The domain layer holds the rules: for Media, upload intake, lifecycle (retry, edit, delete) and applying results; for Processing, command handling, the Attempt lifecycle and recovery. It decides whether a change is allowed, makes it, and stages any outgoing message in the same transaction. The persistence layer (SQLAlchemy models and Alembic migrations, one history per database) stores it. The shared kernel supplies the message envelope and the outbox/inbox machinery, identical in both images. The FFmpeg command builder is a separate pure package with no I/O, used only by the encoders.
Relationships that deliberately do not exist
- Media never calls Processing, and Processing never calls Media.
- Neither service can read the other's database. Each function's IAM role can read only its own service's connection string, and the database refuses the other service's login.
- The encoder cannot send messages. It reports only by writing Processing's database; Processing's outbox publishes the result.
These are checked, not just documented: a build step fails if the other service's package, or any retired code from the old design, can be imported inside an image. check_runtime
Infrastructure is shared. Both services are defined in one CloudFormation stack, so network, queue and IAM changes for either service ship together; only code is released per service. The shared kernel is copied into both images, so a breaking contract change needs a release of each.
3cDomain-driven design, and how producers and consumers interact
Two bounded contexts, each with one aggregate that is its consistency boundary: the Asset in Media and the Job (with its Attempts) in Processing. Everything that crosses between them is a translated message, and a handful of fences make those messages safe to deliver late, twice or out of order.
Bounded contexts, context map and language
A bounded context is the part of the system in which a word has one exact meaning and one model enforces its rules. The proposal drew the boundary from the verbs of the workflow (upload, submit, claim, encode, complete, play). The detailed analysis then checked it against what the code actually has to keep consistent inside one transaction.
| Context | Owns | Does not own |
|---|---|---|
| Media Management | Accounts and login, ownership, upload intake, source versions, playback signing, the public job view, deletion and source cleanup (media_db) | Job state, attempts, leases, outputs. It holds only a projection. |
| Processing | Jobs, attempts, leases, retry and cancel, output descriptors, cleanup of late outputs, encoder claims and launch reservations (processing_db) | Users, Assets, source bytes (it has read-only access), playback links |
Why the line is there. In media_db, assets, upload grants and request keys all have a foreign key to users; the authorizer, the upload grant and the playback signer all read those same rows. Owner and Asset belong in one transaction. Processing's rules (one job per video, one current attempt, a lease that decides which worker may finish) need none of that data; they only need to know the owner's ID as a plain value. Processing holds the owner as a UUID, never a foreign key.
The relationships on the context map:
- Customer and supplier. Media is the customer: it says what should be processed. Processing is the supplier and owns the answer.
- Translation on both sides (an anti-corruption layer). Media builds a
submitmessage from its Asset and pinned source, and turns each result into its own projection and public status. Processing turns each command into its own rows. Neither imports the other's code. - Published language and shared kernel. The message envelope, the owner-identity format and two OpenAPI documents. The code that defines them is copied into both images, which is why it counts as a shared kernel: changing it affects both sides, so it has a versioning policy (see contract).
Ubiquitous language
| Term | Meaning here |
|---|---|
| Owner | The account that uploaded an Asset; the only one that may read, retry, edit, delete or play it |
| Asset | An owned video and the edit operations to apply. Its ID is also the public job ID. |
| Upload reservation | A 15-minute grant, scoped to one owner, to write one object to storage |
| Source pin | The exact bytes Processing may read: the S3 object version, plus its size and SHA-256 |
| Job | Processing's unit of work for one Asset; exactly one per Asset |
| Attempt | One numbered try at a Job; never reused |
| Lease | A worker's time-limited right to finish one Attempt, judged on the database clock |
| Output descriptor | Kind, key, size and SHA-256 of one output file |
| Command, work, result | The three message families: Media → Processing, Processing → encoder, Processing → Media |
| Projection | Media's own copy of a Job's state |
| Tombstone | Deletion recorded as state (a deleted_at time) rather than removing the row |
There are five message kinds, all in one envelope: submit, retry and cancel (Media to Processing), work (Processing to an encoder) and result (Processing to Media). There are no separate domain events such as "JobStarted". Every change to a Job (claim, completion, failure, retry, cancel) produces one result carrying the Job's full state and an increasing state_version. This style is called event-carried state transfer. It is not event sourcing: the SQL rows are the truth, and messages are copies of it.
Asset, Job and Attempt
An aggregate is a cluster of rows that is changed only through its root, inside one transaction, so its rules always hold. FlickPond has two, and no transaction ever spans both.
| Aggregate | Rules it guarantees |
|---|---|
| Asset (Media) root Asset, with upload reservation, source version, request keys, cleanup intent |
Only the owner can read or change it; anyone else gets 404. A reservation is idempotent per owner and request ID. Stored bytes must match the declared size, SHA-256 and file signature. An adopted source cannot change. Adopting a source and staging its submit happen in one commit.Retry only from failed; edit only from done.Delete is a tombstone plus a cancel in one commit; the source is removed only after Processing confirms. |
| Job (Processing) root Job, with Attempts, retry requests, task binding; plus a submission guard per Asset |
One Job per Asset; an identical repeated submit does nothing; a different one for the same Asset is refused. Every command must match the stored owner, Asset, Job and source. Each Attempt only moves forward. A Job returns to queued only through a new Attempt.A worker needs a valid lease to start and to finish; one task claims at most one Attempt. A cancel that arrives before its submit is permanent. state_version only increases, and every state change commits with its outgoing messages. |
Why a Job has Attempts. A retry must not overwrite the history of the failed try, and a slow worker from the old try must not be able to write a result for the new one. Giving every try its own row, number and output folder (jobs/{job}/attempts/{attempt}/) makes "which try is this result for?" a question the database can answer.
queued is a new Attempt, which happens when the owner asks for a retry.States exist at three levels, and they differ on purpose:
| Level | States | Notes |
|---|---|---|
| Attempt (Processing) | queued, processing, succeeded, failed, abandoned, cancelled | abandoned means the worker stopped reporting (lease expired) or the task was stopped. |
| Job (Processing) | queued, processing, done, failed | Follows its current Attempt. Deletion is a tombstone on the Job, not a status value. |
| Public view (Media) | accepted, queued, processing, done, failed, cancelled | accepted is shown after a verified upload and before Processing's first result arrives; Processing never emits it. cancelled comes from a deleted Job. |
Source pin: the bytes checked are the bytes encoded
An upload grant is valid for 15 minutes. During that time the client could upload a second file to the same key, and S3 would accept it. If Processing simply read "the file at this key", it might encode bytes that were never checked. The source pin prevents that: the source bucket keeps every version of an object, and Media records the one version ID it verified. Every later reader asks for that version and nothing else.
| Step | Comes in | What it does and changes | Goes out |
|---|---|---|---|
| 1 · Reserve | Owner's filename, type, size and SHA-256, plus a client request ID | Checks type and the 100 MiB limit; creates a reservation row with a key chosen by the server (staging/{owner}/{reservation}/source). Repeating the same request ID returns the same reservation; the same ID with a different body is refused (409). | A presigned S3 POST, valid 15 minutes, whose policy fixes the key, content type and allowed length |
| 2 · Upload | The file bytes, from the client straight to S3 | S3 enforces the POST policy. No cookie, no API in the path. | A new object version in the source bucket |
| 3 · Finalize | The reservation ID | Reads the object at an explicit version ID and checks size, SHA-256 and the file's leading bytes (its signature). Then, in one transaction: pins the version on the reservation, creates the Asset, and stages the submit in the outbox. Finalizing again returns the same Asset. | 202 with the job ID (equal to the Asset ID) |
| 4 · Every later read | The source descriptor: bucket, key, version ID, SHA-256, size | The encoder downloads that version and recomputes the SHA-256 before encoding. The descriptor travels inside every message; it is never a URL. | Verified bytes for FFmpeg |
The database enforces part of this directly: a finalized reservation must carry a real version ID (a check constraint), and an unversioned bucket is refused. Retry and edit reuse the stored pin, which is why a retry never needs a re-upload.
The client must hash the whole file before reserving; the browser reads it into memory to do so, which is acceptable at 100 MiB but would not be for multi-gigabyte files. A versioned bucket keeps old versions, so cleanup (expired grants, deleted Assets, late writes after expiry) is a standing background duty of MediaRepair.
The encoder's IAM permission to read the source bucket covers the whole bucket, because S3 cannot scope it to one owner. The binding to the owner's prefix and the pinned version is enforced in Processing's code before any read.
The full upload-to-playback trace through AWS is in 4d.
Outbox and inbox: moving a change from one database to another
The problem. Finalize must do two things: save the new Asset in media_db and tell Processing about it through SQS. These are two different systems and there is no transaction that covers both. If Media commits and then crashes before sending, the video is never processed. If it sends first and then fails to commit, Processing works on an Asset that does not exist. This is the dual-write problem.
The outbox. Media does not send anything during the request. It writes the message as a row in its own message_outbox table, in the same transaction as the Asset. Either both exist or neither does. A separate step sends outbox rows afterwards.
The inbox. The sender may send a row twice (it cannot always know whether its last send succeeded), and SQS itself may deliver a message more than once. So every receiver first writes the message's ID and a hash of its content into its own message_inbox, in the same transaction as the change the message causes. A second delivery finds the ID already there and does nothing. The receiver tells SQS to delete the message only after that commit.
submit row in outbox: one commit| Step | Comes in | What it does and changes | Goes out |
|---|---|---|---|
| Stage | A domain change that needs a message | Inserts the message body, its target queue and a content hash into the outbox, inside the domain transaction. Never commits on its own. | An outbox row due now |
| Publish | A due outbox row | Locks the row with SKIP LOCKED (two senders never take the same row), stamps a claim token and commits. Sends to SQS with no database lock held. Then marks it sent, but only if the claim token still matches. On failure it backs off (2, 4, 8 … up to 60 s). | The message on SQS |
| Accept | A message from SQS | Inserts its ID and content hash into the inbox inside the domain transaction. Already present with the same hash: skip. Same ID with different content: reject as a conflict. | True (apply) or false (duplicate) |
| Acknowledge | The committed result | The Lambda reports only failed records; SQS deletes the rest. A failing message returns after the 420 s visibility timeout and moves to a dead-letter queue after 5 receives. | Deleted message, or a retry |
| Repair | A one-minute tick | Sends anything still due; recreates work for queued Attempts whose message has gone missing (SQL is the source of truth, the queue is only transport) | Re-sent messages |
Who sends what: Media's commands are sent only by MediaRepair, on its one-minute tick, because the MediaApi function has no SQS permission. ProcessingCommands sends its own outbox right after its commit. An encoder's result (claim, done, failed) waits in Processing's outbox until the next repair tick, or until an S3 "object created" or ECS "task stopped" event triggers the same repair pass sooner. Each send of a work message also wakes the launcher.
Because only the one-minute tick sends Media's commands, a submit can wait up to about a minute in the outbox before it reaches the queue.
The outbox gives up immediacy and adds a table, a sender and repair logic to each service. In return a state change cannot be lost between the two databases, and Media keeps accepting uploads while Processing is unavailable. On AWS, with Processing's command consumer switched off for 48 s, Media still accepted an upload (202) and the job reached done 58.9 s after the consumer came back. r1018b
What happens when a message arrives twice
Delivery is at least once: every message arrives one or more times, possibly late and out of order. Exactly-once delivery is not available across a database and a queue, so each receiver is made idempotent: applying the same thing twice has the same effect as applying it once. Several layers each catch a different kind of repeat:
| Repeat | What stops it having an effect |
|---|---|
| The same message delivered again | Inbox: the message ID is already recorded, so the handler does nothing and the message is deleted. |
A second submit for the same Asset with a new message ID | Submission guard: one row per Asset, locked first. An identical request is a no-op; a different one is refused. |
A cancel that arrives before its submit | The guard records the cancel; a later submit is accepted as a no-op and never creates work. |
A retry sent twice | Retry requests are unique per Job and request ID, so the second creates no new Attempt. A retry that overtakes its submit is rolled back, including its inbox row, so a later redelivery can succeed. |
Two copies of the same work | The work message ID is fixed per Attempt and state version. The first encoder to claim moves the Attempt to processing; the second finds it no longer queued and drops the message. |
An old or reordered result | The projection ignores anything with a lower state_version or an older Attempt (see projection). |
| A client repeating a request after a timeout | Reserve is idempotent per owner and request ID; retry and edit carry a request key; the Publisher stores an intent key per file and reuses it when it reruns. |
Duplicates do occur in practice. In a nine-job burst on the live environment, the work queue received 18 sends for nine jobs; all nine reached done and the queues drained to zero without manual purging. LV-11
A check that killing a worker mid-encode never leaves duplicate outputs has not been run on AWS. The fences that should guarantee it (lease token, Attempt output prefix, cleanup of dead Attempts) are tested locally on real PostgreSQL.
Lease: which worker may write a result
Several things can try to finish the same Attempt: a duplicate work message, an encoder that was presumed dead but is only slow, or an old encoder still running after the owner retried. The lease decides which one is allowed to write.
| Action | Comes in | What it does and changes | Goes out |
|---|---|---|---|
| Claim | Job and Attempt IDs from a work message | Locks the Job, then the Attempt. Requires both queued, the Attempt to be the Job's current one, the Asset not deleted, and the Attempt not bound to another task. Sets both to processing, writes a new random lease token, a lease expiry 60 s ahead and a deadline (900 s on Fargate, 720 s on Lambda). Stages a result. | The lease token to the worker, or nothing (the worker drops the message) |
| Heartbeat | The token, every 10 s | If the lease is still live, pushes expiry another 60 s (never past the deadline); a Fargate encoder extends its SQS message's visibility at the same time | True, or false: the worker stops |
| Finish | The token and the output descriptors (or an error) | Checks exactly one primary output, all keys under this Attempt's folder, size and SHA-256 present. Then, under lock, requires the same token and an unexpired lease and deadline. Writes done with outputs, or failed. | A result in the outbox; the worker deletes its work message |
| Expiry | A repair tick, or an ECS "task stopped" event | For a current Attempt whose lease or deadline has passed: Attempt abandoned, Job failed ("retry the stored source"), cleanup of its output folder scheduled | A failed result to Media |
All times are read from the database clock (clock_timestamp()), never from the worker, so a worker with a wrong clock cannot extend its own lease. No database lock is held while FFmpeg runs or files transfer.
A worker dies mid-encode. It stops heartbeating. If ECS reports the task stopped, the event handler fails the Attempt at once; otherwise the lease runs out within 60 s and the next repair tick does it. On AWS, a deliberately stopped encoder was noticed in 5.8 s against a 300 s target. r1017b The owner then retries: a new Attempt, a new output folder, the same pinned source. If the old worker was only slow and later tries to finish, its token no longer matches the current Attempt and the write is refused; anything it uploaded sits in the old Attempt's folder and is deleted by the cleanup scan, which repeats for a day to catch late writes.
There is no automatic requeue after a worker failure: the Job becomes failed and the owner decides whether to retry. A video that crashes the encoder therefore cannot loop forever, but the owner sees a failure that a second try might have fixed. The one automatic successor is the short lane handing a too-long clip to Fargate (4 · Lanes).
Projection: Media's own copy of each job
Media must answer "what is the status of my video?" and sign playback links without calling Processing. It keeps a projection: one row per Asset in processing_projections, holding the Job ID, current Attempt and number, state_version, status, outputs and error. Only MediaResults writes it, inside the same transaction as the inbox row.
| Comes in | What it checks | What changes | Goes out |
|---|---|---|---|
A result: full Job state at a state_version |
The Asset exists for that owner; the Job ID matches; the source equals Media's own pinned source; done has exactly one primary output; every output key is under jobs/{job}/attempts/{attempt}/. Older state_version: ignored. Same version, different content: rejected. Older Attempt: ignored. A finished Attempt cannot change. A deleted Asset ignores everything but the cancel confirmation. |
The projection row, and the Asset's link to its Job | Nothing; the browser reads it on its next poll (every 2 s) |
Reads then never leave Media: GET /jobs/{id} loads the Asset (filtered by owner) and its projection, and signs links to the outputs listed there. The output-prefix check means even a malformed result cannot make Media sign an arbitrary object.
The projection is eventually consistent: it can lag Processing by the time a result takes to be sent and applied, and a lost result leaves it stale until repair or a newer result. In exchange, status polling, playback and the retry and edit pre-checks never depend on Processing being up, and Processing's database sees no read traffic from users.
Who may do what
FlickPond has one kind of user who owns things, the owner, and an operator role for admin routes. Access is checked at four layers, each by the component that owns the data:
| Layer | Mechanism | What it prevents |
|---|---|---|
| Session | Login sets a signed token in an HttpOnly, Secure, SameSite=Strict cookie; scripts in the page cannot read it. | Token theft by page scripts; cross-site requests |
| Gateway | The Media authorizer runs before every protected route of both services. It verifies the cookie, reads the current user row (no caching, so a deleted user is refused at once) and returns the owner ID and role. The adapter in front of the application code drops any client-supplied identity headers and builds the identity only from the authorizer's answer. | Anonymous calls (401); forged identity headers |
| Application | Media loads every Asset by ID and owner; Processing filters every Job by owner. A miss is 404, so another owner's video looks like it does not exist. Admin routes require the operator role, read from the current user row. | Reading or changing another owner's Asset; non-operators on admin routes (403) |
| Infrastructure | Each function has its own IAM role. Queue policies deny sending to or reading from a queue to every role not listed as its producer or consumer. Database logins are per service, and the runtime login cannot change the schema. | A compromised function reaching the other service's queue or data |
These were tested on AWS: anonymous requests got 401 on all job routes, forged identity headers changed nothing, a direct SendMessage from a non-producer was refused on all three queues, and each service's login was refused by the other's database. security negatives
The API Gateway address is reachable without CloudFront, and there is no web application firewall; the authorizer and one stage-wide rate limit are the only protections there. The authorizer costs one database read per request, and because it reads Media's users table, Processing's public routes depend on Media's database being available.
Network placement, IAM roles in detail and security scanning are in 4 · Network and 5 · Scanning.
Producers, consumers and the public contract
Producers create Assets; consumers play the output (section 1b defines the roles). Both reach the platform only through the public HTTPS API under /api/media. Neither has storage credentials, queue access or database access.
Producer contract: getting a video in
| Call | Client sends | Platform does | Client gets |
|---|---|---|---|
POST /uploads/reservations | Request ID, filename, type, size, SHA-256 | Creates a 15-minute grant (see source pin) | Reservation ID, Asset ID, presigned POST fields |
| POST to S3 | The bytes, with the presigned fields, no cookie | S3 enforces key, type and length | Success from S3 |
POST /uploads/reservations/{id}/finalize | Nothing else | Verifies and pins; creates the Asset; stages submit | 202 with the job ID |
GET /jobs, GET /jobs/{id} | — | Reads Asset and projection | Status (accepted → queued → processing → done or failed), and when done, signed links |
POST /jobs/{id}/retry | Request key | Only from failed: stages retry; a new Attempt over the stored source | 202 |
POST /jobs/{id}/edit | Operations (clip, crop, scale, convert), request key | Only from done: copies the output to a new pinned source and creates a derived Asset | 202 with the new job ID |
DELETE /jobs/{id} | — | Tombstone and cancel in one commit; source deleted after Processing confirms | 204 |
Consumer contract: playing it
When the job is done, the job view carries a presigned URL to the MP4 that expires within 15 minutes; S3 serves it with range requests (206), so the player can seek. For HLS, the player requests the playlist through Media at /jobs/{id}/hls/master.m3u8; Media checks ownership and returns it with caching disabled. Each segment request is answered with a 307 redirect to a fresh presigned S3 URL. Video bytes therefore never pass through the API, and every playback still passes an owner check. Only file names matching a strict pattern are served.
Two clients on the same contract
The browser app is plain JavaScript with vendored hls.js and Plyr for playback. It hashes the file with the browser's crypto API, runs reserve → upload → finalize, and polls the job every 2 s. The Publisher CLI publishes a whole folder: for each file it reserves, uploads with a separate cookie-free HTTP client, finalizes, and optionally waits. It keeps a private journal of pending intent keys, indexed by file name, size and SHA-256, so a rerun after an uncertain network response reuses the same key and cannot create a duplicate Asset. It reports an outcome per file and exits non-zero if any failed.
Contract versioning
The HTTP contract is published as two OpenAPI documents (Media and Processing, both 1.0.0), generated from the code; a test fails if they drift. The message contract is one envelope with a schema_version. The rule for change: additions only within a version; consumers accept the current and the previous version and ignore fields they do not know; producers keep emitting the old version until every consumer reads the new one. Each consumer keeps a fixture file listing the fields it reads, and the producer's tests check its real messages against it. Additive changes can be released in either service first; a breaking change takes two releases.
Only version 1 has ever existed, so accepting "the previous version" is tested by raising the version number in tests, not by a real second version in production. The compatibility of a released pair of services is still an operator's attestation that those tests support.
How a release of one service is made and rolled back is in 5 · Continuous delivery and 5 · Rollback.
Questions a professor may ask
Why two services and not four (identity, media, processing, delivery)?
A service boundary is worth its cost when the two sides have different rules, data and reasons to change. Processing does: attempts, leases, retries, and a CPU-heavy load that scales separately. Identity and delivery do not: every playback or retry decision needs owner and Asset together, which today is one query in one database. As separate services, the authorizer, the upload grant and the playback signer would each need a call or a replicated copy of user data, and a delivery service would need to ask Media for ownership on every segment. That adds latency and failure modes without any independent scaling or release need. The proposal already rejected four services; the detailed domain analysis confirmed it against the actual foreign keys in the code.
The cost of staying at two: Media is the larger service and holds several concerns. If sharing or a second identity provider arrived, identity would be the next candidate to split.
Why not keep one database with two schemas? It would be cheaper.
Logically FlickPond already had that in V1: two databases on one Aurora cluster, with separate logins. That enforced ownership (neither login can read the other's tables), which is the property DDD needs. What it did not give was failure and capacity isolation: one instance, one capacity ceiling, so a burst of encoder writes or a failed resume affected both. On 21 October Processing was moved to its own cluster, created as a copy-on-write clone of the shared one; once a smoke test passes, each cluster's copy of the other service's database is dropped.
The cost is a second cluster's storage and its own resume delay after idle. Both clusters still scale to zero. A shared schema with cross-schema queries would have been cheapest of all, but it would let one service quietly depend on the other's tables, which is exactly what Project 1 suffered from.
Why asynchronous messages instead of a REST call from Media to Processing?
With a synchronous call, an upload succeeds only if Processing is up at that moment, so the two services' availability multiplies. With a queue, Media commits the upload and its outgoing message locally and returns; Processing picks it up when it can. This was shown on AWS: with Processing's command consumer off, Media accepted an upload and the job completed after the consumer came back.
The price is that delivery is at least once and possibly out of order, so the system needs the inbox, the submission guard, the lease and the projection fences. Status also becomes eventually consistent, which is why Media keeps its own projection. The alternative of keeping Redis/RQ was rejected because it needs a server running all the time, which conflicts with scaling to zero.
SQS is already durable. Why do you need an outbox?
SQS durability starts only once SQS has the message. The risk is the moment before: the Asset is committed in PostgreSQL, but the send to SQS has not happened or its reply was lost. There is no transaction spanning PostgreSQL and SQS. The outbox makes the intent to send part of the database commit, so a crash can only delay the message, never lose it. A lost reply just means the row is sent again, and the receiver's inbox absorbs the duplicate.
Alternatives: change data capture from the database log (more infrastructure), or a two-phase commit (not supported by SQS). The outbox costs a table and a sender per service.
Is processing exactly once?
Delivery is not; the effect is designed to be. Messages can arrive more than once, and work messages do (18 sends for nine jobs in one live burst). What prevents a double effect is layered: the inbox drops repeated message IDs, the submission guard allows one Job per Asset, a claim succeeds only on a queued Attempt, a finish needs the current lease token, and the projection ignores older versions. So the same video may be picked up by two encoders, but only one can claim it, and only the lease holder can record a result.
What is not yet proven on AWS is the case of a worker killed mid-encode followed by a retry, checked for duplicate output files. The fences that should prevent it are tested locally.
What happens if an encoder dies halfway, or an old encoder finishes after a retry?
The dead encoder stops renewing its 60-second lease. An ECS "task stopped" event, or the next repair tick after expiry, marks the Attempt abandoned and the Job failed; on AWS this was noticed in 5.8 s. The owner retries, which creates Attempt 2 with its own output folder over the same pinned source. If the first encoder was only slow and tries to finish, its lease token belongs to Attempt 1, which is no longer current, so the database refuses the write. Its files sit under Attempt 1's prefix and are removed by the cleanup scan.
An automatic requeue was rejected so that an input that crashes the encoder cannot loop. The cost is that a transient failure needs the owner's click.
Is this event sourcing, or CQRS?
Not event sourcing: the authoritative state is ordinary SQL rows in each service, and messages are snapshots copied from them; nothing is rebuilt by replaying a log. There is a separation of reads and writes in one place: Media's projection is a read model built from Processing's results and serves all status reads. That is a projection, not a full CQRS architecture: within each service, reads and writes use the same tables. Full Job snapshots were chosen over fine-grained events because they make out-of-order delivery easy to handle: the newest state_version simply wins.
Are the services really independent? What still couples them?
Independent: data (separate clusters and logins), code (a build fails if one image can import the other), release (each service is promoted and rolled back on its own, with the other unchanged), and runtime business flow (no synchronous calls). Still coupled: Processing's public routes depend on Media's authorizer and therefore Media's users table; both are defined in one CloudFormation stack, so infrastructure changes ship together; and the contract code is a shared kernel, so a breaking change needs two releases. These were accepted as proportionate for a three-person team; separate stacks per service and an identity provider outside Media would remove them at the cost of more operations.