AWS Builder Center
Building a Narrative Intelligence Pipeline on AWS with Databricks, Kubernetes and LLMs

Building a Narrative Intelligence Pipeline on AWS with Databricks, Kubernetes and LLMs

How to turn a constant stream of social media and news posts into searchable, AI-detected narratives, and the AWS patterns that keep it reliable and affordable.

Data Platform Engineer



The problem

Analysts who track public conversation don't want to read millions of individual posts. They want to know which stories are forming, who is pushing them, and how fast they spread. A single viral claim can show up as thousands of near-identical posts across X, Reddit, TikTok, Telegram and news sites, in several languages.
A narrative intelligence pipeline has to:
  1. Collect posts from many providers, each with its own format.
  1. Reshape them into one consistent schema.
  1. Enrich every post with machine learning: classifications, named entities, bot and location signals.
  1. Group related posts into narratives using large language models (LLMs).
  1. Make the results searchable for analysts.
This article walks through a reference architecture for that pipeline on AWS. It is based on patterns I have worked with in production. Most of the system runs inside one AWS account per environment. A few parts are external services, and I call each of those out along with the AWS-native option you could use instead.

What runs on AWS and what doesn't

Component
Where it runs
AWS-native alternative
Spark processing
Databricks on AWS. Compute runs on EC2 in your account; Databricks manages the control plane
Amazon EMR, AWS Glue
Data lake storage
Amazon S3 (Delta Lake format)
—
ML enrichment service
Amazon EKS
Amazon SageMaker endpoints
Container images
Amazon ECR
—
LLM rate limiter and API cache
Amazon ElastiCache for Redis
—
LLM response cache
Amazon DynamoDB
—
Credentials
AWS Secrets Manager
—
Access control
AWS IAM (instance profiles, IAM roles for service accounts)
—
Data providers
External news and social media APIs
—
LLMs
External: OpenAI API
Amazon Bedrock
Search index
Elasticsearch (Elastic product, not an AWS service)
Amazon OpenSearch Service
CI/CD
External: GitHub Actions
AWS CodeBuild, AWS CodePipeline
Alerting
External: PagerDuty
Amazon CloudWatch alarms + Amazon SNS
The rest of the article goes through the pipeline stage by stage. For each stage it covers which AWS services are involved and how they connect.

Databricks on AWS

Databricks is the processing engine for stages 2 to 4. On AWS, a Databricks workspace has two parts:
  • Control plane: run by Databricks. It hosts the web UI, the job scheduler and notebook storage.
  • Compute plane: runs in your AWS account. Spark clusters are EC2 instances inside your VPC, and the data stays in your S3 buckets.
This split matters for security reviews. Post data never leaves your account. Databricks clusters reach AWS services with an IAM instance profile attached to the cluster, so no access keys are stored anywhere.
Two Databricks features do much of the work:
  • Delta Lake on S3 gives you ACID writes, schema enforcement and time travel on top of plain S3 objects.
  • Unity Catalog manages table permissions. Each environment (development, staging, production) gets its own catalog, and each catalog maps to its own AWS account and S3 buckets.

Stage 1 and 2: Ingest and normalize

Services: external data provider APIs → Databricks on AWS → Amazon S3

Pulling from external providers

The data providers are external APIs outside AWS. Each one has its own pagination style, rate limits and failure modes. Ingest jobs on Databricks pull data on a schedule and write the raw responses to S3 before doing anything else.
Keeping raw data in S3 means you can re-run normalization without calling the providers again. That saves money and gets around their rate limits. Use S3 lifecycle rules to move old raw files to S3 Glacier storage classes.
External APIs fail all the time, so every client needs retries. Use exponential backoff with jitter, and only for errors that are worth retrying:
import random
import time

import requests

RETRYABLE = {429, 500, 502, 503, 504}

def get_with_retries(session, url, params, max_retries=5, base_delay=1.0):
for attempt in range(max_retries + 1):
try:
resp = session.get(url, params=params, timeout=30)
except requests.RequestException:
if attempt == max_retries:
raise
else:
if resp.status_code not in RETRYABLE:
resp.raise_for_status() # 4xx errors fail fast
return resp.json()
if attempt == max_retries:
resp.raise_for_status()
time.sleep(base_delay * 2**attempt + random.uniform(0, 1))
A 429 or 503 will probably succeed later, but a 401 or 404 never will. The random jitter stops hundreds of Spark tasks from retrying at the same moment and overloading the API again. AWS's own SDKs use the same approach, and the AWS Architecture Blog post "Exponential Backoff and Jitter" explains why it works.
Provider API keys live in AWS Secrets Manager. More on that below.

One schema for every source

Each provider names its fields differently. A post's text might be  body ,  fullText ,  content  or  selftext . Instead of writing a custom parser per source, define the mapping in config:
# normalizers/reddit_submission.yaml
fields:
post_id: { path: "id" }
author: { path: "author" }
text: { path: "selftext", transform: strip_markdown }
url: { path: "url" }
posted_at: { path: "created_utc", transform: epoch_to_timestamp }
platform: { constant: "reddit" }
A shared base normalizer reads the YAML, validates required fields, applies the transforms and writes a Delta table to S3. Adding a new source then mostly means writing a new YAML file.

Stage 3: Enrich with an ML service on Amazon EKS

Services: Databricks on AWS → Amazon EKS (pulls images from Amazon ECR)
The enrichment models (text classifiers, named-entity recognition, bot detection, location signals) run as an HTTP service on an Amazon EKS cluster in the same AWS account. The Databricks job sends posts in batches and writes the returned labels back to Delta tables on S3.
Why a separate service instead of running the models inside Spark?
  • Independent scaling. The model service scales on its own EKS node group and can use GPU instance types without changing the Spark clusters.
  • Independent releases. A new model version ships as a new container image without redeploying the pipeline.
  • Reuse. Other applications in the account can call the same service.

Keep traffic private

Databricks clusters and the EKS cluster run in the same VPC (or in peered VPCs), so the job calls the service through an internal endpoint, never through the public internet. Traffic stays inside AWS, latency is lower, and you don't need a public load balancer.
Keep the endpoint in per-environment settings rather than in code:
# settings.toml
[development]
ml_service_url = "http://ml-service.dev.svc.cluster.local"

[staging]
ml_service_url = "http://ml-service.staging.svc.cluster.local"

[production]
ml_service_url = "http://ml-service.prod.svc.cluster.local"
from dynaconf import Dynaconf

settings = Dynaconf(settings_files=["settings.toml"], environments=True)
ML_SERVICE_URL = settings.ml_service_url
Moving the service to a new cluster, or promoting it from staging to production, becomes a config change with no code edits.

Images in Amazon ECR

CI builds the service image and pushes it to Amazon ECR, and EKS pulls it from there. Turn on ECR image scanning to catch known vulnerabilities, and add lifecycle policies to remove old untagged images.
In this setup CI runs on GitHub Actions, which is outside AWS. It authenticates to AWS with GitHub's OIDC provider and an IAM role, so no long-lived AWS keys are stored in GitHub. If you prefer to keep CI inside AWS, AWS CodeBuild and CodePipeline do the same job.
AWS-native alternative: if you'd rather not run a cluster, host the models on Amazon SageMaker real-time or batch endpoints and call them from Databricks the same way.

Stage 4: Detect narratives with LLMs

Services: Databricks on AWS → external OpenAI API, with Amazon DynamoDB and Amazon ElastiCache for Redis in between
This stage turns enriched posts into narratives:
  1. Cluster near-duplicates so that 5,000 copies of one claim count as a single item.
  1. Discover candidate narratives with an LLM over representative posts.
  1. Retrieve matching posts for each candidate using multilingual embeddings.
  1. Confirm matches with an LLM. A small fine-tuned model works well for this classification step.
  1. Merge and deduplicate narratives that describe the same story.
The LLMs are external. In this architecture they come from the OpenAI API, which runs outside AWS, so prompts leave the AWS network. If your data must stay inside AWS, Amazon Bedrock provides foundation models through an AWS API with IAM authentication and VPC endpoints. The caching and rate-limiting patterns below work the same with either provider.
LLM calls are the most expensive and most rate-limited part of the pipeline. Two AWS services keep them under control.

Cache every prompt in Amazon DynamoDB

Pipelines re-run. A backfill, a failed task or a reprocessed batch often sends the exact same prompt again. Hash the model and prompt, and store the completion in DynamoDB:
import hashlib

import boto3

table = boto3.resource("dynamodb").Table("llm-completions-cache")

def cached_completion(client, model, prompt):
key = hashlib.sha256(f"{model}:{prompt}".encode()).hexdigest()
item = table.get_item(Key={"prompt_hash": key}).get("Item")
if item:
return item["completion"]

resp = client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
)
text = resp.choices[0].message.content
table.put_item(Item={"prompt_hash": key, "model": model, "completion": text})
return text
Why DynamoDB works well here:
  • On-demand capacity absorbs the spiky load of a Spark job with no capacity planning.
  • Key lookups take single-digit milliseconds, so a cache hit costs very little.
  • TTL can expire old completions automatically.
  • A gateway VPC endpoint keeps traffic from Databricks to DynamoDB off the internet at no extra charge.
The Databricks cluster's instance profile needs only  dynamodb:GetItem  and  dynamodb:PutItem  on this one table.

Share one rate limiter across Spark workers with ElastiCache

LLM providers enforce requests-per-minute and tokens-per-minute limits per model. A Spark job may run hundreds of tasks across many EC2 instances, and none of them knows what the others are sending. A per-process limiter can't work here. The workers need shared state, and Amazon ElastiCache for Redis provides it.
A minimal tokens-per-minute limiter:
import time

import redis

r = redis.Redis.from_url(REDIS_URL)

def try_acquire(model, tokens, tokens_per_minute):
window = int(time.time() // 60)
key = f"tpm:{model}:{window}"
used = r.incrby(key, tokens)
r.expire(key, 120)
if used > tokens_per_minute:
r.decrby(key, tokens) # give the budget back
return False
return True
Workers call  try_acquire  before each request and wait briefly when it returns  False . If bursts at window edges become a problem, a sliding window or token bucket written as a Lua script gives smoother traffic.
Run ElastiCache in private subnets of the same VPC, with in-transit encryption turned on ( rediss://  URLs). ElastiCache Serverless is a good fit when load varies a lot between runs. The same Redis cache also stores responses from upstream provider APIs, so repeated lookups of the same post or user don't go back to the provider.

Stage 5: Search with Elasticsearch

Services: Databricks on AWS → Elasticsearch → analysts
The final job writes narratives and their posts to an Elasticsearch index, where analysts search by keyword, entity, platform or time range.
Elasticsearch is an Elastic product, not an AWS service. You can run it yourself on EC2 or EKS, or use Elastic Cloud hosted on AWS. The AWS-native option is Amazon OpenSearch Service. It started as a fork of Elasticsearch and has a similar API, and it adds IAM authentication, VPC access and managed upgrades.
Whichever engine you use:
  • Size shards to the data. Oversized shards slow down queries and recovery, and very small shards waste memory. Check document counts per shard after each load and reshard when an index outgrows its target.
  • Write in bulk from Spark. Use the Spark connector or the bulk API with sensible batch sizes. Single-document writes are far too slow at this volume.
  • Keep the writer credentials in Secrets Manager, separate from the read-only credentials analysts use.

Security on AWS

AWS Secrets Manager for every credential. Provider API keys, the LLM API key and search credentials are read at runtime:
import json

import boto3

def get_secret(name, region):
sm = boto3.client("secretsmanager", region_name=region)
return json.loads(sm.get_secret_value(SecretId=name)["SecretString"])
Name secrets by environment, for example  dev/pipeline/llm-api  and  prod/pipeline/llm-api , so IAM policies can limit each environment to its own secrets.
IAM roles everywhere, no access keys:
  • Databricks clusters use an instance profile with access only to the S3 buckets, DynamoDB table and secrets they need.
  • EKS pods use IAM roles for service accounts (IRSA) or EKS Pod Identity.
  • GitHub Actions assumes an IAM role through OIDC federation.
Network:
  • Run Databricks compute, EKS and ElastiCache in private subnets.
  • Add gateway VPC endpoints for S3 and DynamoDB, and an interface endpoint for Secrets Manager.
  • Only the calls to external APIs (data providers and the OpenAI API) go out through a NAT gateway.
Account separation: development, staging and production each get their own AWS account. Use AWS Organizations to manage them.
Secret scanning: a pre-commit hook such as  detect-secrets  blocks credentials before they reach the repository.

Deployment and operations

  • Infrastructure as code. Supporting AWS resources such as ElastiCache clusters and Secrets Manager entries are defined with Pulumi, an external tool. AWS CDK or AWS CloudFormation work just as well if you want to stay with AWS tools.
  • Pipelines as code. Databricks Asset Bundles describe jobs, task dependencies, clusters and parameters in YAML. CI deploys the bundle to each environment's Databricks workspace.
  • Feature-branch deployments. Pushing a branch that follows a naming convention deploys an isolated copy of the jobs, so you can test against real data without touching shared environments.
  • Alert on duration as well as failure. A job that silently runs for 20 hours is as bad as one that fails. In this setup alerts go to PagerDuty, which is external. On AWS you can get the same result with CloudWatch alarms that publish to Amazon SNS.
  • Cost controls. Use Spot Instances for Databricks worker nodes where jobs tolerate interruption. Add S3 lifecycle rules for raw data, use DynamoDB on-demand capacity for the cache, and tag all resources by environment so AWS Cost Explorer can break down spend.

Lessons learned

  1. Land raw data in S3 first. Storage is cheap. Re-running from S3 is much cheaper than calling providers again.
  1. Put source differences in config. YAML normalizers kept the code small as the number of sources grew.
  1. Treat LLM calls as a scarce shared resource. Caching in DynamoDB and shared rate limiting in ElastiCache reduced both cost and throttling errors.
  1. Keep models behind a service on EKS. The ML service scaled and shipped separately from the data pipeline.
  1. Keep endpoints and secrets out of code. Per-environment config and Secrets Manager made migrations and promotions routine.
  1. Know what leaves AWS. Label every external dependency clearly (providers, the LLM API, CI, alerting) and know the AWS-native alternative for each one.

Wrapping up

Most of this pipeline uses standard AWS building blocks: S3 for the data lake, EC2 compute under Databricks, EKS and ECR for the ML service, DynamoDB and ElastiCache to control LLM usage, and Secrets Manager and IAM for security. The external pieces are the data providers, the LLM API, Elasticsearch, CI and alerting. Each sits at a clear boundary, and each has an AWS-native alternative: Bedrock, OpenSearch Service, CodePipeline and CloudWatch.
If you're building something similar, or have handled LLM rate limits at scale another way, I'd like to hear about it in the comments.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article