11 KiB
Async video, reusable feed ranking and musical discovery
Implemented on 2026-11-07. This extends the earlier scaling iteration. It changes application behavior and prepares the staging deployment; external Atlas, S3/CDN and multi-host failover have not been verified in this environment.
Background video lifecycle
With VIDEO_JOBS_ENABLED=true, video publication stages the source and immediately
creates a post with processingStatus=pending. Conversion does not run in the HTTP
request. An independent worker claims pending posts from MongoDB and generates MP4,
HLS and an optional thumbnail before atomically changing the post to ready.
The job is embedded in the same post write, so a successful pending-post creation
cannot lose a separate queue enqueue. Workers use atomic claims, 60-second leases,
10-second heartbeats, bounded attempts (default 3), and exponential retry delays capped
at five minutes. Expired final attempts become failed rather than remaining stuck
in processing. A lease token, source URL and undeleted-post condition guard publication.
Lease expiry can cause duplicate computation; only the current owner can publish.
Each attempt writes to a separate directory and cleans its own unsuccessful artifacts.
Normal feeds, lists and search exclude pending, processing and failed posts. The owner can fetch their individual post to inspect its status; non-owners cannot fetch unfinished posts. Internal job metadata is excluded from queries and response transforms. Pending posts cannot be edited; video replacement in async mode requires creating a new post. Text/image/audio behavior and the existing synchronous mode remain available.
Client flow
- Request
POST /api/v1/media/uploads/presignwith folderposts/video, MIME and size. - PUT the file to the returned
uploadUrlusingrequiredHeaders. - Submit multipart/form-data to
POST /api/v1/postsor/api/v1/posts/reels, withvideoStorageKeyset to the returnedstorageKey, plus optional caption/style/maqam. The existing multipart-only post contract also applies to posts containing only fields. - Read
processingStatusfrom the created post. Poll the owner's individual GET endpoint untilreadyorfailed. The existing response-envelope setting still applies. - For a failed post, its owner can call
POST /api/v1/posts/:id/video/retry; retries are throttled. It returnsprocessingStatus=pending.
Multipart videoFile uploads also stage their source when async mode is enabled.
Arbitrary videoUrl values are rejected in async mode. Direct-upload keys must be under
the authenticated user's video prefix, have valid size/type/owner metadata and an ETag.
The worker reads the configured managed storage, with an ETag precondition for direct
uploads, rather than fetching arbitrary HTTP URLs. Overwriting an enqueued object causes
that job to fail; upload a new key instead of mutating an active source.
Job conversion is strict: disabled/missing ffmpeg, codec/HLS failures, excessive duration or lost ownership cannot silently publish the original as a successfully processed file. The existing 100 MiB source limit and 7200-second duration ceiling apply. Shared process admission limits from the previous iteration still apply. Server-staged source files are removed after successful publication; direct-upload sources are retained because the same owned object may have other references. Include these sources and failed-job sources in the deployment's explicit storage-retention policy.
Worker operation
Local async operation requires API and worker to share the same local storage directory:
npm run build
# Set VIDEO_JOBS_ENABLED=true and VIDEO_PROCESSING_ENABLED=true in the intended environment.
npm run start:prod
# In a separate process, with the same database/storage environment:
npm run start:video-worker
VIDEO_JOBS_ENABLED defaults to false to preserve existing local clients. The supplied
scale profile enables it and now includes a separate video-worker image target/service.
Production replicas use S3, not independent container-local files. The worker runs no
HTTP listener. MongoDB is the durable job store; BullMQ remains available for existing
unrelated application jobs. Pending-job age, failed jobs, source retention and worker
process health need operational monitoring in the real deployment.
Reusable feed ranking
When both FEED_CACHE_ENABLED and FEED_RANKING_CACHE_ENABLED are true, the first page
stores a compact ranking snapshot containing only post IDs, scores and ranking time.
Subsequent pages use the same ordering instead of fetching and scoring the candidate
pool again. New first-page heads are scoped by feed invalidation versions; an existing
cursor can finish its frozen ordering across engagement/version changes.
Snapshot keys include viewer identity and ranking filters/limit. Explicit
followingOnly=true is separate from the default following feed, whose empty-feed
fallback can include discovery content. Every uncached page reapplies current post
visibility, blocks, private/disabled-author and reported/not-interested exclusions while
loading selected rows. No complete candidate documents or media arrays are cached in
the ranking snapshot.
The default snapshot TTL is 90 seconds (FEED_RANKING_CACHE_TTL_SECONDS, range 30–300).
Cursors remain opaque; version 2 includes a snapshot ID. rankingExpiresAt is an epoch
millisecond timestamp. Response caches do not extend snapshot validity. On 410 Gone,
clients reload the first page. Changing ranking filters or page size starts a new feed.
Legacy cursors and disabling ranking snapshots retain the previous behavior.
Musical discovery and collaboration
GET /api/v1/users/discover now accepts:
| Parameter | Meaning |
|---|---|
instrument |
Exact instrument, with case/Arabic vowel compatibility |
maqam |
Musical maqam |
genre |
Music genre |
location |
Literal location substring |
latitude, longitude |
Supply together; zero coordinates are valid |
radiusKm |
1–500, default 30 when coordinates are supplied |
Geographic filtering combines scalar bounding ranges with an exact spherical distance
test, including polar and dateline behavior. The existing public-talent restrictions
still exclude disabled/private accounts. Optional instrument, maqam and genre
fields are also stored on general/post collaboration requests, without changing their
existing approval and authorization flow.
Feed ranking now gives an explicit, bounded boost to a post's style/maqam when it matches the viewer's musical preferences, including Arabic normalization. This is a heuristic extension to the existing ranking, not a newly trained recommendation model.
Arabic search and request costs
Compatibility search treats input literally while matching Arabic vowel marks, tatweel and common alef forms; punctuation cannot become executable regex. Empty/mark-only queries are rejected. Global search/suggestions coalesce repeated policy/relationship lookups within a single request using AsyncLocalStorage. They do not cache privacy or block policy across requests.
Atlas index definitions now retain standard analyzers and add an Arabic multi analyzer
to names, captions and musical text fields. Opt-in Arabic query paths are controlled
by SEARCH_ARABIC_ANALYZERS_ENABLED. This follows the primary
MongoDB multi-analyzer
and query-path documentation.
The supplied staging profile uses users_search_v2 / posts_search_v2, and disables
automatic regex fallback so an unavailable production search service is visible.
Deploy the v2 definitions and wait until the Atlas indexes are READY/queryable before enabling those query paths. The existing synchronization command creates/updates indexes; its return does not itself prove index-build completion. Actual Atlas relevance/latency still needs representative Arabic/English queries on the target cluster.
Deployment and verification
Local performance sample
An isolated run used 50000 text posts, 60 synthetic users, concurrency 16 and ten seconds per workload. Redis/external services were disabled. The ranking snapshot used the local cache. To isolate ranking reuse from full-response caching, the cursor kept the selected second page fixed while page metadata varied, producing distinct response-cache keys.
| Workload in this run | Req/s | Average ms | p95 ms |
|---|---|---|---|
| Next page, ranking/cache disabled | 19.59 | 813.23 | 938.52 |
| Same next-page selection, ranking snapshot enabled, response cache missed | 35.91 | 442.47 | 548.63 |
| First-page full response cache | 381.39 | 41.92 | 75.92 |
| Uncached first page | 18.32 | 869.67 | 1047.61 |
| Compatibility search | 18.24 | 855.51 | 1368.86 |
All recorded HTTP requests succeeded. Snapshot-enabled pagination observed approximately 1.83x throughput and 41.5% lower p95 in this short local comparison. Cache modes differ; this is not a promise for production hardware or a distributed-system capacity test. Cold first-page/search latency remains material, and actual Arabic Atlas latency is unmeasured. Raw results.
Rollout commands
Build and inspect the additive indexes first. The new feature-index command includes feed order indexes, the video-claim index and the artist-discovery indexes:
npm run build
npm run db:feature-indexes -- --dry-run
# For the intended database, pass MONGODB_URI explicitly, then:
npm run db:feature-indexes
# Set the intended Atlas index names/environment and run:
npm run search:sync-indexes
docker compose --env-file .env.scale -f docker-compose.scale.yml config --quiet
docker compose --env-file .env.scale -f docker-compose.scale.yml up --build -d
The current .env and pre-existing Postman work were not modified. Example settings,
DTOs, worker entrypoint and Compose are the reviewable rollout artifacts. Update the
client upload flow before enabling async mode for its deployment.
Validation includes the complete unit/coverage gates, real local MongoDB, real synthetic ffmpeg conversion, competing claims, an independent worker process, abandoned final-attempt recovery, owner-only retry, hidden pending posts, and musical discovery across the dateline. Arabic fallback search is tested against real documents. Atlas multi-analyzer query construction is unit-tested; the external Atlas service is not available here.
The complete coverage run passed 101 suites / 1068 unit/integration tests, including the runtime-service coverage gate (91.33% statements, 92.09% lines, 91.54% functions, 74.86% branches). The existing 21 E2E cases and six new isolated video/discovery/Arabic- search cases passed across the full and focused runs, including ordinary expired-lease recovery. Build, ESLint, Compose configuration and additive feature-index dry-run checks passed. Actual Docker image construction remains blocked by the unavailable daemon.
Docker Compose configuration is validated, but the Docker daemon is unavailable. Actual container builds/routing, distributed Redis/Socket.IO, S3/CDN I/O, multi-host failures and multi-hour mixed-load soaks remain unverified. Local synthetic text/video checks do not establish production-scale capacity.