Lesson 1: Twitter MVP Foundation

Lesson 4 60 min

Realtime Feed Reliability — Integrated Social Media Platform

Scope

This document describes how the integrated Twitter-style MVP wires authentication, timeline reads, event-backed writes, cache layers, realtime fanout, and operational visibility into one coherent production surface. The React operations console and CLI verification scripts exercise each domain independently and together.

Architectural placement

Component Architecture

TWITTER MVP SYSTEM ARCHITECTURE - INTEGRATION CORE CLIENT APPLICATION LAYER GATEWAY / SECURITY PLANE CORE APPLICATION RUNTIME ENGINE DISTRIBUTED STORAGE & STATE INFRASTRUCTURE React Web UI Dashboard Triggers Demos Auth Validation & Rate Limiter Token Validation & Header Parsing Timeline Read Engine Cache-Aside Evaluation Logic Tweet Write Lifecycle Engine DB Persistence & Fanout Manager Redis Memory Cache timeline:user:cursor:limit keys PostgreSQL Database Persistent Tweets & Profiles Event Append Store & WS Fanout Messaging Core HTTP Requests GET /api/timeline POST /api/tweet 1. Lookup Cache 2. On Cache Miss 1. Persist Tweet 2. Append Event 3. Invalidate Cache

The platform treats PostgreSQL as source of truth, Redis for cache and pub/sub, and a Node/Express API with a React dashboard. Observability flows through Prometheus, Grafana, and Jaeger. The integration layer binds schema design, tweet persistence, hybrid timeline generation, WebSocket delivery, L1/L2 caching, JWT auth, versioned HTTP APIs, full-text search, media ingestion, health probes, load smoke checks, and deployment readiness signals.

Request path

  • Browser console invokes domain-specific verification actions.

  • API enforces JWT auth and token-bucket rate limits.

  • Read traffic prefers Redis; misses hydrate from PostgreSQL.

  • Writes commit to Postgres, append to the event store, publish Redis notifications, and push WebSocket payloads.

  • Health and info endpoints return checkedAt / fetchedAt for freshness proof.

Core mechanisms

Cache hit vs miss on reads
Timeline and search responses must be correct on miss and fast on hit. Both paths require explicit test coverage.

Event append on writes
Tweet creation updates durable state and emits an auditable event so downstream consumers and realtime clients stay aligned.

Operational timestamps
checkedAt on /health and fetchedAt on /api/info let operators and QA confirm live responses without inferring staleness.

Deterministic verification
Each console verification action must change or refresh at least one visible metric: counts, rate-limit headers, latency, object keys, or JSON payloads.

Data and control flow

Flowchart

TWITTER REALTIME FEED DATA & CONTROL FLOW ENGINE STAGE 1: INGRESS & SECURITY SCREENING STAGE 2: APPLICATION DATA ROUTING PATHS STAGE 3: METRICS SINK & TELEMETRY Inbound Request Arrives Identity & Rate Limits Evaluates Token Security Margins Request Operation? READ FEED Query Redis Cache Key lookup: timeline:user:* Cache Hit? Yes (Fast-path Return) No (Miss) Query Postgres & Hydrate Populate Missing Cache State WRITE TWEET Write State & Fanout Event Postgres DB + Event Appends Append Realtime Response Return UI Output Frame payload Expose Operational Probes Track checkedAt / fetchedAt Live Counter

Timeline read (hybrid fanout)

  • Load follower graph metrics for the requesting user.

  • Select pull, push, or hybrid materialization strategy.

  • Resolve cache key timeline:{userId}:{cursor}:{limit}.

  • On miss, query timeline_entries and supporting tables, then populate cache.

Tweet write

  • Insert row into tweets.

  • Append tweet.created (or related) to events.

  • Fan out timeline_entries to author and followers.

  • Publish notifications:{userId} and tweet_events on Redis.

  • Invalidate timeline and related cache keys.

Request lifecycle

State Machine

TWITTER TIMELINE & TWEET REQUEST LIFECYCLE STATE DIAGRAM STATE INITIAL RECEIVED Inbound API Event auth_pass IDENTITY VALIDATED AUTHENTICATED Token Verified check_limit VOLUME CHECK PASSED RATELIMIT_OK Quota Window Clear cache_found cache_miss OPTIMIZED FAST PATH CACHE_HIT In-Memory Delivery FALLBACK ACTIVATED CACHE_MISS Database Query Hydration TERMINAL SINK SUCCESS checkedAt/fetchedAt Emitted
StateMeaning
RECEIVEDHTTP request accepted
AUTHENTICATEDJWT validated
RATELIMIT_OKToken bucket permits request
CACHE_HIT / CACHE_MISSRead path branch
SUCCESSResponse returned
RETRYABLE_ERROR / TERMINAL_ERRORFailure classification

Naming these states explicitly supports SLO design, on-call runbooks, and trace correlation.

Implementation workstreams

Timeline cache
Adopt key pattern timeline:{userId}:{cursor}:{limit}. Honor cache bust via _t query parameter on operational reads.

Write pipeline
Tweet service must persist, version, fan out, emit events, and call cache invalidation in one transactional boundary where possible.

Freshness metadata
Health and info handlers attach ISO timestamps on every response.

Console metrics by domain

DomainVerification signal
Data modelingUser, tweet, event counts from /api/stats
Tweet storageNew tweet ID and feed length
TimelineModel type, generation ms, item count
RealtimeAudit total, live feed length, WebSocket status
CachingHit rate delta, L1 keys, warm-cycle ms
AuthenticationUsername, tier, JWT suffix
API surfacev1/v2 counts, X-RateLimit-* movement
SearchResult count, trending tag count
MediaObject key, CDN URL, upload latency
MonitoringHealth JSON, stats after probe write
LoadParallel health timing, OK count
DeploymentHealth status, checkedAt, API info

Local runtime

From the application repository root:

bash
cd backend && npm install && npm run build
cd ../frontend && npm install && npm run build
cd ..
docker compose up -d --build backend frontend

Or run processes directly:

bash
cd backend && npm run dev
cd frontend && npm run dev

Expected: API on port 4000, dashboard on port 5173.

Containerized runtime

bash
chmod +x start.sh test.sh demo.sh stop.sh
./start.sh

Expected: compose health checks pass; dashboard serves at http://localhost:5173.

Verification

bash
./test.sh
./demo.sh

Acceptance:

  • Unit and integration tests exit zero.

  • demo.sh reports all domain checks passed.

  • Manual probes return changing timestamps:

    bash
    curl -s http://localhost:4000/health | jq .checkedAt
    curl -s http://localhost:4000/api/info | jq .fetchedAt
    

Demo credentials: [email protected] / demo123!

Gemini integration

Load the Gemini API key from environment only. Never commit secrets to source, scripts, or documentation.

python
import os
api_key = os.getenv("GEMINI_API_KEY")
if not api_key:
    raise RuntimeError("Missing GEMINI_API_KEY")

Extension: idempotent media upload

Add Idempotency-Key header support on POST /api/media/upload. Duplicate keys for the same user must return the original object metadata without reprocessing. Surface idempotency status on the media console panel. Persist (user_id, idempotency_key) → object_key and add regression tests for initial upload and replay.

Acceptance criteria

  • Repeated console verification runs update visible metrics across auth, API, search, media, monitoring, load, and deployment domains.

  • demo.sh completes with zero failures.

  • Health and info timestamps differ between consecutive probes.

  • Cache warm cycles show measurable hit-rate and key-count movement.

Operational summary

Production readiness here means observable, repeatable behavior across read and write paths—not a single successful manual call. Treat cache keys, event append, fanout channels, and freshness fields as first-class contracts the same way schema migrations and API versions are.

Questions & Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *