Twiscope: a shared backend for a growing media-intelligence platform
Twiscope is an Arabic/English platform for media monitoring, analysis and decision support. Its public suite now spans account and topic analysis, influencer intelligence, AI-assisted report analysis, channel monitoring and more. This study focuses on the shared backend scope I built: X analysis pipelines, Decision Hub (Sadeed), the alert engine, subscriptions, access control and the service edge on AWS.
- Backend product areas covered here
- 5
- Data sources integrated
- 6
- As sole backend developer
- 2 yrs
- Gateway in front of 4 services
- Kong
- The problem
- Turn data from multiple sources into useful reports and decision dashboards without blocking user requests during collection and analysis.
- My role
- Built the original backend, then built and directly managed a team of up to 13 engineers. Remained hands-on in architecture, code and production while owning hiring, performance reviews and delivery.
- A key decision
- Run collection and analysis in background jobs, reuse collection windows, and validate versioned snapshots before publishing AI-assisted analysis.
- The result
- Internal production logs showed a comparable workflow of about 100,000 posts falling from over five hours to around three minutes on unchanged server resources. This includes workflow and caching improvements, not just sentiment inference.
The problem
What needed solving
Communications and research teams in the region need to understand conversations about keywords, accounts, influencers and brands on X and other networks — in Arabic as well as English. Generic social-listening tools handle Arabic poorly and don't map to how these teams work.
The backend scope covered by this study had five product areas on one platform: deep on-demand reports, influencer monitoring by quarter, decision dashboards that score a brand against its competitors, scheduled alerts and notifications — all sharing the same data collection, subscriptions and organisation permissions.
Constraints
What the design had to respect
- X API v2 has strict rate limits and a cost per request, so every collection path needs budgets and quotas.
- Subscriptions are per product and per platform, with daily and monthly quotas, shared across an organisation.
- Organisations have roles (owner, admin, member, viewer) that every product must respect.
- Collection and analysis can take minutes; none of it may block an API request.
- For two years the backend had one developer, so the design had to stay operable by a very small team.
Architecture
How the system fits together
Requests enter through a Kong gateway that verifies JWTs and rate-limits before routing to a FastAPI auth service, the Django/DRF backend, a realtime lookup service and the Sanad AI service. Heavy work runs in Celery; Elasticsearch holds snapshots, alert events and the news feed.
Clients
Web app
Angular application with a React 3D view (built by teammates; I own its packaging and deployment).
Influencers Impact app
Flutter mobile app built by teammates on the backend's APIs.
Edge
AWS load balancer → Kong 3.8
DB-less declarative config: RS256 JWT verification, rate limiting, CORS, and a unified API docs portal.
Auth service (FastAPI)
Issues RS256 access and refresh tokens; compatible with the existing Django password hashes.
Services
Django/DRF backend
About 25 apps: Deep-In, Influencer Impact, Decision Hub, Alert System, subscriptions, organisations.
Realtime lookup service
On-demand live queries to X, TikTok, Instagram and Google.
Sanad AI
Retrieval-augmented assistant; exchanges report and enrichment events over SQS.
Notifications service (FastAPI)
Push and email delivery with its own Celery workers.
Async and data
Celery + Beat
Redis broker; queues for reports, Decision Hub, scheduled reports and sentiment backfills.
PostgreSQL (RDS)
Relational data and report results.
Elasticsearch
Decision Hub snapshots, alert events, the news feed, word rollups, and logs.
SQS · S3
Report-ready and enrichment-done events with Sanad; media storage.
Infrastructure
Terraform on AWS
VPC across two availability zones, an Auto Scaling group and internal load balancer per service, GPU instance for AI inference.
Delivery
GitHub Actions on self-hosted runners: security gate, restart, health check, AMI bake, launch-template update, rollback.
Observability
Prometheus metrics for Django and Celery, Elastic APM, logs in Elasticsearch.
Products
What runs on the platform
Deep-In
On-demand analysis reports.
- X keyword reports via full-archive search, with reply enrichment under a per-run request budget.
- X account timeline and mentions analysis.
- Word, hashtag, emoji, country, top-account and engagement aggregates, plus sentiment from a pretrained-model service.
- Instagram, TikTok and Google keyword, hashtag and account reports on demand.
- Completed reports publish an event to SQS so Sanad AI can write summaries back.
Collection runs per report; only the news feed is ingested continuously.
Influencer Impact
Influencer monitoring by category and quarter.
- Staff-managed influencer categories; monitoring a category for a quarter runs a timeline analysis for every influencer in it.
- Per-period aggregates and Elasticsearch word rollups feed category rankings, top words, hashtags, emoji and sentiment.
- Dashboard hardening: concurrent composite indexes, a per-user Redis response cache, a burst throttle, and cache hit/miss metrics.
X only. The mobile app was built by teammates.
Sadeed / Decision Hub
Decision centres that score a brand against its competitors.
- A decision centre holds a brand, followed accounts, competitors and keywords, refreshed hourly, every six hours, or daily.
- A Beat dispatcher starts one Celery chord per centre: parallel per-entity collection, then a single scoring callback.
- Six deterministic weighted indices — reputation, satisfaction, reach, impact, opportunity and risk — with weights versioned per user or globally.
- Tenant-scoped Elasticsearch snapshots power trends and scoreboards; stored windows can be replayed and rescored.
X only. Forecasting is not implemented.
Alert System
Scheduled monitoring with deduplicated digests.
- Each alert gets its own Beat schedule (every 15 minutes by default, at least every 5).
- AND-combined conditions on keyword, mention, sentiment, language and location, with cooldown and minimum-match gates.
- Deduplication by a database unique constraint per alert and item; events are also indexed in Elasticsearch, with a repair command if that write fails.
- One digest per scan by email or HTTPS webhook; webhook targets must resolve to public IPs, checked at save time and send time.
The engine supports X. Delivery is at-least-once.
Notification System
In-app, push and email delivery.
- In-app notification records that clients poll.
- Firebase push and SMTP email through a FastAPI service with its own Celery workers.
- Pending, sent and failed states; retries only for transient errors; Redis idempotency keys suppress duplicate sends.
Built mainly by teammates; I scaffolded the service.
Engineering decisions
What was chosen, and why
A modular monolith first, services where boundaries were clear
With one backend developer, the products started as Django apps sharing subscriptions, permissions and data, with all slow work in Celery tasks. Pieces with clear, independent boundaries — authentication, notifications, the AI assistant, live lookups — were split into their own services behind the gateway.
One collection strategy, three consumers
X collection is implemented once and selected per caller: reports persist results to PostgreSQL, alerts fetch and evaluate without persisting, and Decision Hub collects under a reply-enrichment budget. Rate-limit handling honours X's reset header and falls back to capped exponential backoff.
Chords so scores are comparable
Decision Hub fans out collection for every entity in a centre in parallel and scores them all in one callback at the same instant, so a brand and its competitors are measured against the same window. A per-centre lock prevents overlapping runs, and each run is recorded.
Deterministic, explainable scoring
Indices are weighted formulas over normalised components such as sentiment share, authority, volume, engagement and momentum. If a component can't be computed it is marked absent and the remaining weights are renormalised rather than silently scored as zero.
Deduplicate in the database
Alert events rely on a unique constraint, with each insert in its own savepoint so a duplicate is a cheap no-op. Elasticsearch documents reuse the database id, which makes re-indexing idempotent.
Authenticate at the edge
Kong verifies RS256 tokens and applies rate limits before traffic reaches any service, and authentication moved out of the monolith into a FastAPI service that issues the tokens while staying compatible with existing password hashes.
Trade-offs
What those choices cost
Monolith with shared Celery workers
Fast to build and operate with one developer; today one worker container consumes all main queues, so a heavy queue can delay others.
Scheduled alerts instead of streaming
Predictable cost under X API limits, but alerts arrive on their schedule (minutes), not in real time.
Deterministic indices
Explainable and stable, but no forecasting.
On-demand collection
API spend only when a report is requested; there is no continuous archive except the news feed.
Self-managed Elasticsearch on EC2
Full control and lower cost, at the price of operating backups and upgrades ourselves.
Outcomes
What it delivered
Faster end-to-end processing
I led workflow and caching optimizations that reduced a comparable collection-and-analysis workload of approximately 100,000 posts from over five hours to around three minutes on unchanged server resources. The timings come from internal production logs for this workload. It includes caching and broader workflow changes; it is not a measure of sentiment inference speed alone.
Five backend product areas, one platform
In the scope covered here, Deep-In, Influencer Impact, Decision Hub, the Alert System and notifications share collection, subscriptions, permissions and infrastructure.
Six data sources
X API v2, EnsembleData for Instagram and TikTok, Google Custom Search, LinkedIn, and a news feed indexed into Elasticsearch every five minutes.
A secured service edge
Every request passes JWT verification and rate limiting at the gateway; services sit in private subnets behind internal load balancers.
Repeatable deployments
Production deployment runs on a self-hosted runner only after the automated SAST/SCA security gate passes for the exact commit being released. The workflow checks out that commit, backs up and restarts the service, validates its health, and updates the machine image, with rollback on failure. Additional security validation runs against pre-production.
My role
- Sole backend developer from October 2023 to October 2025; I took on team leadership in August 2024 alongside the backend role and remain the largest contributor (about 70% of backend commits overall).
- Built the X analysis pipelines and the shared clients for X, Instagram, TikTok and Google.
- Built Decision Hub (Sadeed) end to end and the Alert System engine; a teammate built most of the alert delivery tasks.
- Built the influencer-monitoring backend, subscriptions and quotas, JWT authentication and organisation roles.
- Built the Kong gateway configuration, the FastAPI auth service, the realtime lookup service, the Terraform infrastructure and the monitoring stack. Designed and operated GitHub Actions deployment workflows with self-hosted runners and security gates tied to the release commit.
- Teammates built the web and mobile frontends, most of the notification service, scheduled reports, file exports, and the LinkedIn and news ingestion.
Scope notes
- The approximately 100,000-post timing comparison is based on internal production logs reported by me. Cache state and cache-hit rates are not published, so it should not be read as a cold-cache benchmark or a platform-wide performance guarantee. No availability percentage is claimed.
- There is no WebSocket or push channel: alerts run on schedules, and the realtime service answers live lookups on request.
- Sentiment comes from pretrained Hugging Face models served by a separate service; no models are trained in this platform.
- The repositories contain large test suites (about 3,300 test functions). The security gate is a mandatory deployment dependency and checks the release commit. Application testing is part of pre-release validation; this case study makes no claim that every test suite automatically blocks deployment.
- Twiscope is an ASAS IT product; this study stays at architecture level and omits internal configuration.
- Twiscope's public product suite has evolved beyond the five backend areas covered here; twiscope.net is the source of truth for current product names and availability.
Next case study
Sanad AI
Twiscope's assistant answers questions about analytics reports in Arabic and English, with supporting sources. I led the architecture, retrieval and prompt design with the AI engineers who implemented the retrieval components. My hands-on work covered the service foundation, ingestion, API integration, deployment and tracing.
Read it