Files
back_end_oudelaa/docs/SCALE_HARDENING.md

163 lines
9.9 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Backend scaling iteration — 2026-11-07
This iteration addresses measured request costs and resource limits. It does not
establish equivalence to Instagram or prove internet-scale capacity.
## Implemented
- **Two-stage personalized feed.** Ranking queries select only IDs, type, timestamp,
engagement counters and hashtags, with lean author ranking fields. No candidate is
hydrated into a Mongoose document. Only selected page IDs are loaded with complete
response fields and existing media transformations. Their original rank order and
scores are preserved. The second query reapplies post visibility/deletion/moderation
filters; the service rechecks current author disabled/private flags. Removed selections
still advance the cursor so they cannot trap a client on the same page.
- **Recent-feed index.** `feed_recent_order_v1` supports the recent-candidate scan.
`npm run db:feed-indexes` now adds three named feed indexes without dropping other
indexes. Set `MONGODB_URI` explicitly for the intended database before running it.
- **Cache lease cleanup.** Both personalized and Trending feeds release acquired fill
leases in `finally`, including database errors and unavailable viewers.
- **Bounded media processes.** Image conversion, video conversion/HLS and ffprobe share
one process-admission service per API instance. Defaults: two active children, eight
waiters, five-second queue wait and 120-second execution limit. Stdout is capped at
256 KiB and retained stderr at 64 Ki characters. Timed-out children are killed and
retain their slot until process close. Shutdown kills active children and rejects
queued/new work. Admission failures return retryable 503 errors, and do not permanently
mark ffmpeg as unavailable. Existing codec-failure fallback behavior is preserved.
- **Bounded Redis request waits.** HTTP cache/counter connections disable the offline
command queue, allow one retry and set a 1500 ms command / 3000 ms connection timeout.
Queue and pub/sub connections retain their different retry semantics. Redis errors
are rate-limited in logs without logging connection credentials. Cache/counter errors
fail closed instead of silently creating independent per-replica state.
- **Multi-replica staging configuration.** `docker-compose.scale.yml` defines three API
instances, a shared persistent Redis and an Nginx entrypoint. It requires an external
MongoDB replica set and shared S3/CDN configuration. Production startup validation
rejects declared multi-replica operation without Redis, its Socket.IO adapter and S3.
Proxy trust defaults to empty and accepts only explicitly configured IP/CIDR ranges.
The actual `.env` and the existing Postman work were not changed by this iteration.
## Measured results
At 6000 posts and concurrency 8, the same five-second HTTP workload was rerun after
the two-stage feed change:
| Workload | Previous iteration req/s | Current req/s | Previous p95 ms | Current p95 ms |
| --- | ---: | ---: | ---: | ---: |
| Uncached personalized feed | 7.59 | 18.76 | 1114.57 | 523.24 |
| Cached personalized feed | 394.07 | 389.58 | 36.37 | 37.50 |
The observed uncached-feed gain is approximately **2.47x throughput** and **53.1% lower
p95** relative to the immediately preceding implementation's recorded run. Cached
throughput was essentially unchanged. These runs occurred at different times on a
shared laptop and remain short samples; do not interpret their ratios as guaranteed
production improvements. [Current 6000-post result](performance/two-stage-6000.json),
[previous implementation result](performance/after.json).
A second run seeded **50000 posts**, used **16 concurrent requests**, and measured each
workload for **10 seconds**:
| Workload | Req/s | Average ms | p95 ms | Successful requests |
| --- | ---: | ---: | ---: | ---: |
| Uncached personalized feed | 16.58 | 961.12 | 1260.41 | 100% |
| Cached personalized feed | 307.82 | 51.90 | 92.62 | 100% |
| Trending first page | 33.58 | 471.39 | 669.91 | 100% |
| Trending next cursor | 34.17 | 463.67 | 660.68 | 100% |
| Compatibility regex search | 16.80 | 928.10 | 1431.92 | 100% |
[Raw 50000-post result](performance/two-stage-50000.json). This run has a different
concurrency and dataset; it is not a like-for-like comparison with the 6000-post run.
The uncached feed and regex search still show substantial latency under the larger
workload. Production Atlas Search, realistic social graphs, shared Redis, distributed
replicas, media traffic and longer tests were not measured by this local harness.
Real MongoDB checks confirmed **400 lean ranking rows / zero hydrated candidate
documents / 20 hydrated response documents**, and successfully excluded a selected
post deleted between the stages. Trending examined 20 documents for its first page;
at offset 4000 on the larger fixture, keyset examined 248 versus skip's 4020. Keyset
work depends on rank distribution; it is not universally constant. The CI workflow
now runs database-only query/hydration regression checks after building.
## Validation
The complete unit/integration suite passed: **98 suites / 1053 tests**. The final private-
author race check was added afterward and its affected feed suite was rerun. All
**21 isolated E2E cases** passed, as did the build, ESLint and Compose configuration
validation. Tests cover rank order, selected-page size, disappearance/private-author
changes, lease release on errors, media capacity, queue expiry, execution timeout,
shutdown and output limits. Existing media/service tests also exercise process errors.
`npm run test:reliability:smoke` additionally used real ffmpeg and ffprobe processes,
converted a small synthetic video without output files, killed a deliberately hung
Node child, and rejected a cache request against an unused loopback Redis port in
approximately 2.4 ms. This tests the unavailable-connection path, not a running Redis
deployment or its network failover. [Raw smoke result](performance/reliability-smoke.json).
Docker Compose parsed successfully with `.env.scale.example`; the Docker daemon was
not running, so containers, Nginx syntax/runtime, Redis pub/sub, cross-replica Socket.IO,
S3/CDN access and failover were **not** exercised. These are prepared deployment
artifacts, not a claim of tested distributed capacity.
## Run the staging topology
1. Copy `.env.scale.example` to `.env.scale` and replace every placeholder. Single-quote
actual bcrypt hashes to preserve dollar signs in Compose env files. `.env.scale` is
ignored by Git and excluded from the Docker build context.
2. Provision the MongoDB replica set and S3 bucket/CDN. Use identical JWT secrets and
shared storage across replicas. This profile uses the existing in-process notification
path with Redis Socket.IO fan-out; it does not deploy the RabbitMQ notification service.
3. Build and synchronize the three feed indexes on the selected database before starting
the API with production automatic index creation disabled.
4. Validate, then start:
```powershell
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 staging proxy listens only on `127.0.0.1:8080`. It trusts no incoming forwarded
headers and replaces them with its connection peer. The API trusts only the configured
Docker subnet. The fixed subnet must be changed together in Compose and the API proxy
trust setting if it conflicts with the host network. A public TLS ingress needs an
explicit trusted-real-client-IP design; do not assume forwarded client headers survive
another proxy unchanged.
Nginx uses IP affinity for Socket.IO polling and explicit Upgrade/Connection forwarding.
IP affinity can concentrate clients behind the same NAT on one replica. Dynamic Docker
DNS uses upstream `resolve`, which requires Nginx 1.27.3 or newer; the supplied
`stable-alpine` image should be pinned to a verified digest for an actual release.
See the primary [Nginx upstream documentation](https://nginx.org/en/docs/http/ngx_http_upstream_module.html)
and [WebSocket proxy documentation](https://nginx.org/en/docs/http/websocket.html).
This is a single-host staging topology, including one Redis instance. Container restarts
and three API processes do not provide multi-host/database/Redis high availability.
Redis uses `noeviction` because cache, counters and BullMQ jobs share it; monitor its
512 MiB configured budget and separate/cache-size infrastructure as traffic grows.
## Reproduce performance and longer load
```powershell
npm run build
npm run perf:isolated -- --posts 6000 --duration 5 --concurrency 8 --output local-6000.json
npm run perf:isolated -- --posts 50000 --duration 10 --concurrency 16 --output local-50000.json
npm run perf:isolated -- --database-only --posts 50000 --output local-plans.json
npm run test:reliability:smoke -- --output local-reliability.json
```
`--duration` permits up to eight hours per workload, and `--posts` accepts 5000–500000.
The harness seeds in bounded batches, creates its own MongoDB process and test users,
and never uses the application database URI from `.env`. It verifies real candidate
projection, page-only hydration and deletion rechecks in addition to keyset plans.
These text-only, single-process fixtures are regression tools, not representative
media/social-graph traffic or a production capacity promise.
Video processing is still part of the existing upload request. Admission control
bounds subprocess load; it does not create durable, independently deployed media workers.
Keep large uploads on the existing S3 presigned-upload path. A durable media lifecycle
with independent workers/retries, production Atlas Search indexes, long mixed-traffic
soaks and infrastructure failover tests remain work requiring the actual staging services.
The subsequent [async video and ranking-snapshot iteration](ASYNC_VIDEO_AND_FEED_SNAPSHOTS.md)
implements the independent worker lifecycle and additional musical/search features;
the statements above describe the earlier measured iteration.