Back to notes

October 24, 2026 · 24 min read

Building a Video Platform with Flutter and Rust: Playback State, Authorization, and Recovery

Engineering a Flutter video client and Rust backend: episode-switching races, recoverable playback requests, progress concurrency, authorized HLS delivery, caching, and overload protection.

I recently brought the first version of a video platform to end-to-end integration. My work spans the Flutter client, a Rust playback SDK, the Rust Media API, the media-processing pipeline, and delivery through Cloudflare’s edge infrastructure.

Conceptual illustration of authorization and media delivery between a mobile player and backend services
Control requests determine what may be played; the delivery path carries the media bytes. The component boundaries are described below.

Getting a video to play was the easy part. The difficult cases appeared when operations overlapped or failed: an authorization response arrived after the user had moved to another episode; the server created a session, but the phone saw only a timeout; two devices updated the same progress record; or the app returned to the foreground while the native player was still entering picture-in-picture.

These problems cross the UI, native player, client protocol, and database. A fix in one layer may only hide the symptom. Stopping an await does not roll back a server transaction. Cached bytes do not establish playback rights. Clearing a loading indicator does not mean the native player has finished switching sources.

This article focuses on the harder engineering work: coordinating playback state, recovering writes with uncertain outcomes, handling progress conflicts, combining authorization with caching, and protecting the backend from frequent playback reports. Each topic connects a concrete failure scenario to its implementation, tradeoffs, and validation. Code examples are excerpts or simplified representations of the current implementation.

The development playback flow and test deployment rehearsals are complete. Full integration with the production business service, some commercial features, and production acceptance remain in progress. Test-environment results are not presented as production capacity. Deployment addresses, credentials, business identifiers, and real content data are omitted.

Reading guide

QuestionSection
Why must an old request not restore the previous episode?Playback races and lifecycle
How do we recover when the server succeeds but the client times out?Idempotency and checkpoints
Why validate authorization when the segment is already cached?Delivery authorization · Preloading and caching
How do two devices avoid overwriting each other’s progress?Progress concurrency and backend protection
How can these mechanisms be tested?Failure-oriented validation

1. System boundaries and technology choices

Separate control requests from media delivery

Playback creates two different workloads. Catalog queries, authorization, session renewal, and progress updates need identity checks and transactional state. Playlists, initialization segments, and media segments need object storage, caching, and Range delivery.

The Media API handles control requests; Playback Edge handles media delivery. A separate worker performs media processing so that a long-running FFmpeg job does not share an HTTP request’s lifetime.

Flutter App ------------------------------ Business
    |                                      Identity / entitlements
    +-- ViewModel / Repository
    |       |
    |   Dart Facade / FRB / Rust Client
    |       |
    |   Rust Media API ------------------- PostgreSQL
    |       |                              Sessions / progress / catalog
    |       +----------------------------- Optional Redis catalog cache
    |
    +-- PlayerAdapter / native player
            |
        Local HLS proxy and segment cache
            |
        Cloudflare Edge ------------------ Private R2
                                               ^
Media CLI -> Media API -> durable tasks         |
                             |                 |
                      Resource Worker ---------+
                      FFmpeg / packaging / verification

These boundaries do not imply a microservice for every responsibility. The current media deployment uses a single-host Docker template. The API and resource worker share a persistent source volume, while Edge runs separately. This isolates workloads without adding a distributed deployment problem to every component.

LayerImplementationMain constraint
Media serviceRust, Axum, Tokio, SQLx, PostgreSQLEnforce transactional state and bound request/database concurrency
Resource pipelineNode.js, FFmpeg, durable tasksLease-based ownership, retries, verifiable output
Edge deliveryCloudflare Worker, private R2Validate before cache access; separate playlist and object caching
Client protocolRust Client, FRB, Dart FacadePreserve operation identity and recover uncertain requests
Mobile appFlutter, ViewModel, Repository, player adapterCoordinate UI lifecycle, protocol state, and native playback

Rust runs in two distinct environments here. The server accesses the database and issues authorization. The client Rust library ships inside the app and implements HTTP and playback protocols. They communicate through network contracts; they are not the same runtime.

Assign data ownership before designing endpoints

Business and Media are separated by the data they own.

Business owns users, commercial entitlements, homepage composition, and favorites. Media owns the catalog, resource versions, rights windows, publication state, playback sessions, viewing progress, and history. Business does not write Media tables, and Media does not query the order database.

That boundary affects Flutter data composition. A favorites screen gets content IDs from Business, then fills in titles, artwork, and episode information through Media’s card API. Viewing history comes directly from Media. Adjacent UI elements do not necessarily belong to the same backend domain.

The same distinction applies to the homepage. A basic catalog provides media facts; product-specific sections and recommendation order belong to Business.

This avoids cross-service dual writes but requires some client aggregation. Repositories coordinate the sources so that widgets do not need to know which backend owns each field.

2. Races between episode switching and the native player

A valid server session does not mean the player has rendered a frame. The player may still be initializing, buffering, seeking, switching sources, or handling a system interruption.

The ViewModel coordinates user intent. The Repository connects business entitlements with the Media SDK. A PlayerAdapter contains plugin-specific calls. Protocol dependencies and player implementations can therefore be replaced separately, and fake adapters can exercise state transitions.

One playing flag cannot represent three kinds of state

StateOwnerQuestion it answers
User intent and screen stateFlutter ViewModelWhich episode is wanted now? Did the user pause? Is this screen still active?
Protocol and authorization stateSDK and Media APIWhich episode belongs to the session? Is authorization valid? Is a write unresolved?
Actual media stateNative playerWhich source is loaded? Is it initialized, buffering, or producing frames?

These states do not change simultaneously. The user may already want the next episode while the SDK waits for a switch receipt and the native player still holds the previous source. If every callback can update the same playing or currentEpisode field, callback timing determines the outcome.

The implementation uses an epoch to limit which asynchronous results remain relevant, protocol sequences and receipts to track server state, and the player adapter to perform the actual source change. Selecting an episode is not treated as proof that playback has succeeded.

Serial playback operations combined with epoch checks to reject obsolete results
Figure 1. Selecting B changes intent immediately. A finishes without applying its stale result, then the queue executes B.

Use an epoch to reject obsolete results

An episode change can involve fetching entitlements, switching the session, exchanging a grant, and initializing the player. Swiping again does not immediately end those earlier Futures.

Each playback attempt captures an epoch. A new intent increments it, and asynchronous continuations check that they still belong to the current attempt.

// Preserve the combination of serialization and epoch checks.
// Previous-progress saving, navigation, diagnostics, and error handling are omitted.
Future<void> open(String id) {
  final epoch = ++_epoch;
  bool current() => !_disposed && epoch == _epoch;
  final paused = player.pause();

  return _enqueue(() async {
    if (!current()) return;
    await paused;
    if (!current()) return;

    ready = false;
    final source = await repository.open(id);
    if (!current() || _background) return;

    await player.load(
      source.uri,
      initialPosition: Duration(milliseconds: source.positionMs),
    );
    if (!current() || _background) {
      await player.pause(); // Loading already had a side effect: stop it explicitly.
      return;
    }
    ready = true;
    notifyListeners();
  });
}

Navigation responses, native playback attempts, and source-loading results must all belong to the current content. Network cancellation alone cannot enforce that: an operation may already be inside the SDK or waiting on the native player.

Protocol operations run serially through _enqueue. If B is selected while A awaits authorization, the epoch changes immediately, but B’s protocol operation waits for A to leave the queue. When A returns, it sees that it is obsolete and does not load its source.

A useful test holds A’s authorization response, selects B, then releases A. A must never load, and B must execute afterward. Another test selects B after A has entered player.load. The post-load check must pause the obsolete attempt before the queue advances. Checking only the final title misses the possibility that the old video briefly starts playing.

_enqueue is the ViewModel’s serial task queue, not a built-in Dart API. The full implementation also captures failures from the immediate pause and updates errors only for the current attempt.

The epoch boundary: an epoch check prevents obsolete results from changing current client state. It does not undo server writes. Existing sessions and unresolved operations still require protocol-level handling.

Order operations that have side effects

Progress reporting, pausing, switching, and closing have ordering dependencies. During a switch, the protocol may already refer to the new episode while the native player still exposes the old position. That position must not be saved against the new content.

The ViewModel coordinates these operations. The SDK maintains progress and heartbeat sequences and settles relevant in-flight operations before switching or closing. Renewal has a separate execution path so that a slow progress request does not indefinitely block authorization refresh.

This does not mean placing every Future in one queue. Writes to shared state need ordering; independent work can remain concurrent. Poor queue boundaries can create either races or unnecessary blocking.

After renewal, the app still has to apply the new source to the player while preserving position and intent. Updated SDK credentials and a completed native source change are separate events.

Lifecycle handling needs more than foreground and background

On iOS, inactive can mean Control Center or a system dialog. It does not always mean playback should stop. Picture-in-picture may also take ownership of the existing player while the app loses focus.

The lifecycle adapter distinguishes inactive, hidden, paused, and resumed, allowing native PiP handoff to complete. A successful handoff retains playback and restores the inline view on return. A failed handoff falls back to normal background suspension.

This process also has a generation counter. The user can return to the foreground before PiP handoff finishes; a late handoff result must not trigger an obsolete background action.

Lifecycle caseRequired behavior
inactive from Control Center or a dialogDo not automatically treat it as background suspension
paused after successful native PiP handoffRetain native playback; avoid recreating the session
PiP handoff failsFollow the normal background-pause path
The app resumes before handoff completesReject stale callbacks using the generation
The user pauses in the PiP windowDo not force playback when the app resumes

The native player’s current intent matters. A resumed event alone is not a reason to create another session or call play unconditionally.

Lifecycle handling therefore crosses Flutter callbacks, native state, and server-session behavior. A pause in one callback and a play in another are not enough.

3. Recovering playback operations after network failures

Keep protocol state outside Flutter screens

The Media SDK has its own Rust workspace. media-client implements HTTP and playback behavior, media-contracts defines typed models, FRB supplies bindings, and a handwritten Dart Facade provides the stable app-facing API.

Widget / ViewModel
    ↓
App Repository
    ↓
Handwritten Dart Facade
    ↓
Generated FRB bindings
    ↓
Rust Client / Session / Checkpoint
    ↓
Media HTTP API and Edge

App code does not import generated bindings directly. Binding upgrades and model changes stay near the SDK boundary, while the Rust client can be tested without Flutter.

The host supplies valid credentials. The SDK does not take over Business login, purchases, or entitlement acquisition, and it does not own a native player. It tracks session protocol state, sequences, and unresolved operations; the app handles navigation, source changes, and platform behavior.

This avoids scattering protocol requests across screens or making SDK renewal depend on a particular login implementation.

Recovering a committed session after a lost response using the original operation identity and checkpoint
Figure 2. Recovery preserves the original operation identity instead of generating a new key and creating another session.

A timeout is not permission to create another session

A request needs three possible outcomes: confirmed success, confirmed rejection, and an outcome that is still unknown.

The key distinction: a network error describes what the client observed. It does not establish whether the server committed its transaction.

If the client generates a fresh idempotency key after losing a successful response, it may create another session and consume another concurrency slot. Recovery must preserve the original operation identity.

The SDK keeps the unresolved request body, idempotency key, and relevant sequences. It advances state after a confirmed result. When the outcome is unknown, it retains and reconciles the original operation.

OutcomeState to retainNext step
Confirmed successReceipt, sequences, current stateAdvance local state
Confirmed rejectionStable error code and relevant current stateHandle through the protocol or host
UnknownOriginal body, operation identity, pending stateResolve the old operation before starting another

Ordinary GET requests can have bounded transport retries. Writes are handled by the protocol layer. The HTTP method alone does not define recovery semantics; operation identity and server idempotency rules do.

Cancellation is not rollback either. Leaving a screen can cancel local work, but a transmitted mutation may already have committed.

Preserve operation identity across process restarts

A checkpoint contains the session creation key, known session state, progress revision, sequences, and pending operations. With a host-provided persistence callback, the SDK can save recovery material before sending a request.

It does not store Access or Entitlement tokens, Playback Grants, or signed playback URLs. Restoration acquires valid credentials and asks the server to confirm ownership, state, and sequences. A checkpoint is not an offline entitlement certificate.

Stored in a checkpointExcluded from a checkpoint
Original creation key and pending request bodiesAccess / Entitlement tokens
Known session and authorization sequencePlayback Grant
Progress revision and protocol sequencesSigned playback URL

Privacy boundary: token-free does not mean non-sensitive. Viewing positions and account namespaces still need isolation and secure storage.

The app chooses the storage implementation. This app uses secure storage and derives isolation namespaces from the user, device, and service origins.

Snapshots and events also serve different purposes. A snapshot describes current session state; events announce operations or credential changes. Credential events may contain signed URLs, so they cannot share the same logging or persistence policy as token-free snapshots.

Validate recovery through fault injection

Let the server commit, then drop the response in a test transport. Recovery must reuse the original body and operation identity without creating another session. Rebuild the client from a checkpoint and verify that its state converges with the server’s.

Within the server’s idempotency retention window, the same key and body should replay consistently. Reusing the key with a different body must produce a conflict. Otherwise, idempotency can conceal a caller bug.

The useful assertion concerns database state and client state before and after failure, not merely whether a method eventually stops throwing.

4. Carrying authorization through APIs, playlists, and segments

Three credentials with different responsibilities

CredentialIssuerConsumer and purpose
AccessBusinessMedia identifies the user, app, and device context
EntitlementBusinessMedia evaluates the declared content scope and capabilities
Playback GrantMediaEdge restricts asset versions, tracks, and delivery deadlines

The app obtains identity and entitlement credentials from Business, then requests a Media session. Media verifies signatures and checks local account controls, publication state, rights windows, device capabilities, and concurrency limits.

Media then issues a Grant for Edge. Edge does not need order data or Business login credentials: the authorization has been narrowed to specific deliverable resources.

App / SDK          Business          Media             Edge
    |                  |                |                 |
    |-- credentials -->|                |                 |
    |<-----------------|                |                 |
    |-- create session + credentials -->|                 |
    |                  |                |-- validate      |
    |<------------ Playback Grant ------|                 |
    |-- exchange Grant --------------------------------->|
    |<------------ authorized playback material ----------|

Normal authorization does not require a live order-database lookup. The tradeoff is that entitlement changes must propagate through versions and events; a remote order query is not a universal fallback.

Enforce scope in playlists and object requests

Hiding a higher-resolution option in the app is insufficient. An unrestricted master playlist could still expose every track, and a client could request a different URL directly.

Edge verifies the Grant and builds playlists from the allowed video, audio, and subtitle tracks. Object links in child playlists carry signatures and deadlines. Private R2 does not expose a public object path that bypasses delivery authorization.

ResponseCache policyAuthorization boundary
Authorized dynamic playlistprivate, no-storeContains only tracks permitted by the current Grant
Immutable media objectReusable Edge object cacheEvery request reaching Edge is verified first
User progressIsolated from public catalog cachingBound to the current identity and session

Playlists and media objects cannot share one caching policy. Otherwise, a response containing authorization material may accidentally become shared content.

The segment-serving path follows this order:

Validate path, signature, and deadline
    → Look up the Edge cache
    → Read private R2 on a miss
    → Return the full object or a Range response

A hit does not bypass validation. Internal cache keys can identify immutable objects, while authorization is checked before accessing them.

This simplified example preserves that ordering. Helpers are illustrative; the actual implementation also handles preload signatures, path validation, HEAD, and Range requests.

async function deliver(request, env) {
  const object = parseAndValidateObjectPath(request.url);
  const allowed = await verifySignature(object, env, Date.now());
  if (!allowed) return new Response(null, { status: 403 });

  // Authorization must precede cache.match.
  const key = immutableObjectCacheKey(object);
  const hit = await caches.default.match(key);
  if (hit) return hit;

  return readPrivateObject(env.MEDIA_BUCKET, object);
}

Range handling needs correct status codes, lengths, and Content-Range. A partial response must never be cached as a complete object, or a later authorized request could receive incomplete bytes.

Revocation has a propagation window

Entitlement downgrades and account blocks arrive through internal events. Media deduplicates events and advances entitlement or account-state versions so that out-of-order delivery cannot restore older state.

Three moments matter: Business commits a change, Media receives it, and existing delivery links expire. They are not simultaneous.

Events affect subsequent authorization decisions. They cannot guarantee immediate invalidation of every issued URL, and they cannot recall bytes already downloaded. This is time-limited delivery control, not DRM or remote erasure.

Production integration must validate event production, retries, deduplication, and recovery together. A tested Media receiver does not establish the reliability of the entire Business-to-Media pipeline.

5. Progress conflicts and frequent playback reports

Enforce state constraints inside transactions

A playback session depends on account state, device ownership, concurrency limits, content state, and leases. Reading those facts, releasing the connection, and writing later leaves a race between validation and commit.

Relevant writes use transactions and row locks. A progress write first locks and validates the user-control record, then the session, checks app/user/device ownership and session deadlines, and applies sequence and revision rules.

Lock scope and order must remain understandable. The user-control row coordinates related writes but can also serialize a busy user’s operations. Transactions should contain only necessary database work, not waits for object storage or external business services.

Rust’s types distinguish inputs, state, and errors. SQL transactions maintain durable consistency. Choosing Rust does not solve business concurrency by itself.

Arrival order is not progress order

There are two separate races.

Within a session, an older request can arrive late. Session sequences prevent it from overwriting a newer write and distinguish a replay from a different payload using the same sequence.

Across sessions, two devices may read the same progress record and then update it. A session-local sequence cannot order those writes. A shared progress revision supplies the compare-and-set condition.

Device A reads revision 8
Device B reads revision 8

A writes against revision 8 → accepted, revision becomes 9
B writes against revision 8 → conflict, current progress returned

Taking the maximum position is not a correct conflict policy. A user may be seeking backward, rewatching, or restarting. A smaller position can represent the newer intent. The server returns current state so the client can reconcile according to the protocol.

MechanismScopeProblem it handles
Session sequenceOne playback sessionLate writes or conflicting payloads at the same sequence
Progress revisionMultiple sessions for one user/content recordOverwriting a record using an obsolete version
Idempotency keyOne operationRepeating side effects during timeout recovery

The following shows the transaction’s core semantics. Helpers are simplified; the implementation additionally checks identity, session state, request hashes, sequences, and history behavior.

// One transaction: lock the user control, session, and progress records.
let mut tx = pool.begin().await?;
lock_user_and_session(&mut tx, &access, &request).await?;
let current = lock_progress(&mut tx, &access, &request).await?;

if request.expected_revision != current.revision {
    return Err(ProgressConflict { current });
}

let receipt = write_progress(
    &mut tx,
    &request,
    current.revision + 1,
).await?;
save_sequence_and_receipt(&mut tx, &request, &receipt).await?;
tx.commit().await?;

The version check and update occur under the same transaction and locking rules. This avoids a version read outside the transaction followed by an unconditional write.

Heartbeats have their own session sequences. Progress has position and revision rules. A combined reporting endpoint commits both in one transaction to reduce periodic requests without discarding either constraint.

Keep reports from exhausting startup and renewal capacity

An async runtime can wait on many operations; a database cannot execute unlimited work. The API applies admission control before connection acquisition and rejects overload with a stable error and retry hint.

Frequent playback reports have a separate in-flight limit. This prevents heartbeats and progress writes from consuming all database capacity needed for session creation, renewal, and reads. It bounds concurrent work, not requests per second.

Database configuration also limits connection acquisition, statement execution, lock waits, and idle transactions. Admission limits incoming work; the pool bounds database parallelism; timeouts bound how long individual work may occupy resources.

Clients must honor Retry-After and stagger periodic reports with backoff. Otherwise, a rejected batch can return as another synchronized wave.

The middleware uses a non-waiting permit acquisition and holds that permit for the whole request. Diagnostic response extensions are omitted here.

let Ok(_permit) = report_limit.try_acquire() else {
    return (
        StatusCode::SERVICE_UNAVAILABLE,
        [("retry-after", "1")],
        Json(json!({"code": "PLAYBACK_REPORT_OVERLOADED"})),
    ).into_response();
};

next.run(request).await

Concurrency limits are not QPS limits. This bounds active work. When individual operations slow down, admission rejects new work sooner instead of accumulating unbounded waiting ahead of the database.

Progress tests need late sequences, identical replays, conflicting same-sequence payloads, and cross-session revision conflicts. Overload tests should run reports alongside creation and renewal, checking that report saturation leaves room for critical operations.

These controls do not establish a maximum concurrent-viewer count. Capacity depends on reporting intervals, transaction cost, database configuration, and traffic distribution, and requires measurement in the target environment.

6. Making prefetched bytes useful to the player

Shape responses around what the screen uses

Catalog details contain descriptions, credits, and translations. A feed card usually needs only a title, artwork, tags, and episode information. Returning full details for every list item adds database, serialization, network, and parsing work.

The platform provides separate card models and batch APIs. Detail screens request complete records; favorites resolve Business IDs into Media cards; signed-in viewing screens use card-and-progress aggregation.

Public catalog data and private progress retain separate caching boundaries. Aggregating a response must not place a user’s resume position in a public cache.

Localization is also projected on the server: responses carry the selected titles, descriptions, artwork, and tag labels instead of every translation. Cache identity must include the projected language to avoid serving the wrong locale on a hit.

These choices connect Flutter’s actual field requirements to backend queries and serialization. Reducing widget rebuilds alone cannot eliminate the cost of unused data.

Catalog caches do not authorize playback

The implementation includes an optional Redis cache for public catalog payloads and discovery candidates, with payload limits, short I/O timeouts, and bounded loading concurrency. Deployment configuration determines whether it is enabled.

Catalog revisions, publication state, and rights windows affect validity. Cache keys, lifetimes, and read behavior must respect those boundaries; storing JSON for a long time does not make it continuously valid.

Playback creation and renewal do not reuse a catalog cache’s authorization conclusion. A visible card still requires a fresh authorization decision. Stale display data therefore does not directly grant playback access.

Reuse startup playlists during grant exchange

Normal HLS startup involves grant exchange, the master playlist, and child playlists. The SDK and Edge can negotiate a startup bundle containing some playlists in the freshly authorized exchange response, avoiding redundant round trips.

That bundle belongs to the current authorization, resource version, and delivery window. It must not be persisted for long-term use or treated as independent authorization. Unsupported servers or oversized playlists fall back to normal HLS.

This fallback matters because Edge, SDK, and app versions may be upgraded at different times. An optional optimization must not make older combinations unable to play.

Separate authorization checks around the app's local segment cache and the Edge object cache
Figure 3. Local reuse and Edge caching occupy different positions, each with its own authorization boundary.

Connect preloading to the native player’s network path

Downloading segments in Dart does not make the native player use them. The player has its own networking stack. Without a connecting path, preloading can simply consume extra bandwidth.

The app uses a local HLS proxy to connect prefetched bytes to native playback. It registers upstream objects from trusted playlists and exposes a local player-facing endpoint. Reuse requires Edge to have accepted the current full playback authorization.

Memory preloading has a finite budget and keys objects by immutable resource identity, version, and path. Disk caching additionally separates service origins and account namespaces and limits total size, entry size, count, and retention. It persists media bytes, not Grants, signed URLs, or playlists.

Separating immutable identity from temporary URLs permits reuse after signatures rotate without confusing accounts or asset versions.

Scheduling responds to connectivity and screen state. Switching away, entering the background, or buffering can cancel or yield preload work. Cache clearing also has a generation check so that an old download cannot repopulate a cache the user just cleared.

Separate preload authorization → bounded download → immutable bytes

Enter playback → normal playback authorization → validate current scope
                                                       ↓
                                           local proxy reuses matching bytes
                                                       ↓
                                                  native player

The implementation reduces redundant requests and downloads. Actual first-frame gains still depend on device, network, media format, and cache state. A local result cannot stand in for every user’s experience.

Test cache boundaries as well as cache hits

Tests should establish that unauthorized state cannot reach the local reuse path, new asset versions do not hit old objects, account changes do not reuse another namespace, and clearing the cache prevents stale downloads from writing back.

At Edge, populate the object cache first, then request that object with an expired signature. The cache hit must not weaken authorization.

Measure cold starts, memory hits, disk hits, and Edge hits separately. A single total startup time cannot explain where a gain came from and can easily confuse network variance with an implementation improvement.

7. Resource versions and recoverable processing

Model content separately from asset versions

A movie or episode is a content object. Its playlists and segments are resource objects. One content item can have several asset versions without recreating its title, credits, or synopsis every time it is transcoded.

The catalog models movies, series, seasons, and episodes. Resource identifiers and versions link playable content to concrete outputs. This table shows conceptual responsibilities rather than the complete database schema.

ObjectFacts it ownsHow it changes
ContentMetadata, rights, publication, current asset referenceRevision-controlled management writes
Series / Season / EpisodeHierarchy, ordering, episode relationshipsHierarchy and publication constraints
Asset VersionPlaylists, tracks, objects, verification evidenceNew versions with immutable delivery objects
Resource TaskSource, processing mode, stage, lease, resultTask state transitions
Playback SessionUser, device, content, lease, authorization sequenceCreation, renewal, switching, pause, close

Grants refer to a concrete asset version. After an activation change, new grants can use the new version while existing grants continue to reference the original object set. Master playlists and segments do not accidentally mix outputs from separate processing runs.

Rollback means reactivating a verified version, rather than overwriting files at old paths.

Processing, activation, and publication are separate operations

The pipeline supports transcoding, packaging without transcoding, and HLS import. The mode depends on the input and delivery requirements. Upload completion alone does not make content publishable.

Create a content draft
    → Receive and identify the source
    → Queue a durable task
    → Transcode / package / import HLS
    → Build the resource package and object list
    → Upload to private storage; read back and verify size and digest
    → Register the verified resource
    → Explicitly activate the asset version
    → Publish after publication checks pass

Receiving a source, generating output, and verifying uploaded objects are distinct facts. Activation and publication remain deliberate operations.

This permits preparing a version before choosing when to switch. A failed transcode does not replace the active resource, and a successful task does not automatically publish unreviewed content.

Registration validates tracks, object sets, and playlist relationships. Plausible-looking paths alone are insufficient; registered metadata must correspond to deliverable resources.

The CLI can orchestrate catalog creation, uploads, waits, activation, and publication. Each step still passes server-side checks. Automation removes repetition, not validation boundaries.

Leases establish task ownership

Tasks live in PostgreSQL. Workers claim eligible tasks with FOR UPDATE SKIP LOCKED, recording a fresh lease ID, deadline, and attempt count.

The following is a simplified claim operation:

UPDATE resource_tasks
SET state = 'processing',
    lease_id = :lease_id,
    lease_until = clock_timestamp() + :lease_duration,
    attempts = attempts + 1
WHERE task_id = (
    SELECT task_id
    FROM resource_tasks
    WHERE state = 'queued'
       OR (state = 'processing' AND lease_until < clock_timestamp())
    ORDER BY created_at
    FOR UPDATE SKIP LOCKED
    LIMIT 1
)
RETURNING *;

The full implementation limits attempts and handles expired tasks that have exhausted retries. Workers renew leases during processing and attach lease IDs to state updates so that an obsolete worker cannot commit new task state after losing ownership.

Leases provide recoverable execution, not exactly-once external effects. A process can exit after uploading an object but before registering it, or a timeout can occur after storage has accepted the write. Versions, digests, registration rules, and retries must handle these cases together.

The current shared source volume suits a single-host deployment. Cross-machine execution would first require a design for source and intermediate-artifact access. Database claiming does not remove that filesystem dependency.

8. Diagnostics and independent delivery

Preserve correlation without logging credentials

A generic error message rarely explains a cross-layer failure. CLI writes need actor, request, and operation identity. Playback needs session, authorization sequence, and phase. Processing needs task and asset version.

Logs must not include raw Authorization headers, complete signed URLs, or credential-bearing connection strings. SDK errors expose stable codes, request identifiers, and retry hints rather than passing raw request URLs or response bodies upward.

Playback-quality reports use constrained types and error codes and retain the authorization sequence under which they were created. A late report from the previous episode can then be attributed correctly after a switch.

Public examples can explain the design through sequences, models, and error semantics without exposing real headers, internal installation URLs, or business data.

Pin compatible component combinations

Media API, SDK, and App have separate repositories. The platform repository pins their commits through submodules and maintains Edge, contracts, CLI tooling, and deployment inputs.

Server builds do not require Flutter, and the SDK can be verified independently. Compatibility still requires deliberate coordination: API changes must reach contracts, models, servers, and callers, and an SDK commit must exist before downstream repositories reference it.

The platform records a chosen component combination rather than following every remote branch automatically. Reproducibility depends on that combination, not on every repository being independently “latest.”

Deployment separates migrations, API, workers, database, and reverse proxy responsibilities. Source-volume retention, database backups, and R2 delivery objects solve different recovery problems. Production acceptance must establish how these states are restored together, beyond checking that containers start.

9. Validate consistency through failure scenarios

Component tests are necessary, but cross-layer behavior is easier to assess by starting with a failure and checking that every layer follows the same semantics.

The project contains database tests, SDK protocol tests, Edge tests, and app tests. End-to-end environments verify the actual connections between them. The following scenarios define continuing coverage requirements, not a claim that every target environment has passed acceptance.

ScenarioEssential assertionLayers
Creation response is lostRecover the original operation without duplicating the intended session/taskSDK, API, database
Two sessions update progressDistinguish session ordering from shared revision conflictsSDK, progress API
Old results arrive after a switchDo not restore the old source or save its position to the new episodeFlutter, SDK, player
Worker exits during processingRecover after lease expiry; reject stale-owner updatesWorker, task table, storage
Cached object requested with expired signatureEdge still rejects the requestEdge, cache
App resumes during PiP handoffReject obsolete suspension and avoid duplicate sessionsFlutter, native adapter, SDK
Playback reports overload the serviceReject excess reports while preserving room for critical workAdmission control, pool, client backoff

Database tests exercise transactions, locking, and conflicts. Fake players exercise asynchronous ordering. Devices are still necessary for PiP, platform lifecycle, and real playback; protocol tests cannot substitute for them.

Performance diagnostics also need stages: catalog responses, authorization, Edge exchange, first segment, and native first frame. Without that breakdown, “slow startup” gives little guidance on where to work.

10. What the implementation establishes and what it costs

This phase produced four groups of independently testable mechanisms.

Playback coordination. Epochs reject obsolete results, operation ordering coordinates switching and progress, and lifecycle handling accounts for native PiP. This addresses divergence among user intent, protocol state, and the player, beyond UI state alone.

Protocol recovery. The Rust SDK retains idempotency keys, sequences, pending requests, and checkpoints; the server supplies compatible receipts and conflict semantics. Response loss and process termination now have explicit recovery paths, which still need continued testing under real networks and device lifecycles.

Authorization-aware cache reuse. Media defines the playable scope, Edge filters playlists and verifies object requests, and the local proxy delivers legitimately prefetched bytes to the native player. Immutable identity enables reuse; current authorization controls access. First-frame improvements require measurements rather than percentages inferred from architecture.

Backend consistency and resource protection. Transactions, session sequences, and progress revisions handle different races. Separate report admission bounds database pressure. Leases and verifiable output support task recovery. These mechanisms make failures and overload explicit; production capacity remains a measurement task.

There are costs. A Rust SDK adds native builds and cross-language debugging. A local HLS proxy expands player compatibility testing. Shared storage constrains worker deployment. Short-lived authorization and event propagation leave a revocation window.

The next stage is full Business identity, entitlement, and event integration; production capacity and backup-restoration evidence; and broader device coverage. Existing protocols and tests support that work without replacing environment-specific validation.

The value of designing Flutter and the backend together is that a user action can be traced through protocol and durable state: an episode switch has an epoch and authorization sequence, resume has a progress revision, a retry has an operation identity, and cached bytes have an asset version and permitted lifetime. When something fails, those identities make the sequence reconstructable instead of requiring unrelated patches in the screen and server.