Pulls the USGS earthquake feed, filters and reshapes it in Redpanda Connect, then runs a multi-step LLM reasoning loop (hosted Anthropic) over each event in a Python service to produce a regional risk brief: a judgment a plain magnitude rule can't make. Results land in Postgres and are served read-only.
USGS all_hour.geojson ──▶ Redpanda Connect ──▶ topic ──▶ Python worker ──▶ Postgres ──▶ serve
(poll) (filter/dedupe/reshape/enrich) (route→LLM→parse→brief) (read-only API)
How it works: the stage-by-stage data flow is in docs/DETAILS.md; inspection
and test recipes are in docs/MANUAL_TESTING.md.
- Docker with Compose v2 (
docker compose ...). Verified on Docker Desktop (engine 29.x, Compose v5). - An Anthropic API key, needed only to attribute new events. Without one the stack still runs:
the worker skips reasoning (events are stored as
pending) and the seeded sample briefs still serve, so you can explore it keyless. Add the key later and restart the worker, and it reasons over the events it held while keyless.
# 1. (Optional now, required for reasoning) create your local env file
cp .env.example .env
# then edit .env and set ANTHROPIC_API_KEY=...
# 2. Bring up the whole stack
docker compose up -d
# 3. Watch it come up: redpanda and postgres go 'healthy'; Connect starts polling USGS
docker compose ps
# 4. Redpanda Console (topics, consumers), handy for debugging
open http://localhost:8080
# Tear down (‑v also drops the Postgres data volume)
docker compose down -vThe store ships seeded (db/seed.sql), so the API and UI have data the moment the stack is up,
with no API key required. Open the read-only serve layer:
open http://localhost:8000/ # HTML list of briefs (with a legend)
curl -s "localhost:8000/briefs?status=briefed&limit=5" | jq . # JSON, newest first
curl -s "localhost:8000/briefs/<event-id>" | jq . # one brief (404 if absent)Watch live events flow in and get reasoned. The hourly feed is usually all small quakes, so lower the
thresholds in your .env to see volume:
# in .env:
# MAG_THRESHOLD=0.1 let small quakes past the Connect filter
# REASON_MAG_THRESHOLD=1.5 reason on them instead of skipping
docker compose up -d # compose recreates connect + service with the new .env values
docker compose exec redpanda rpk topic consume quakes.filtered --offset start # clean JSON, keyed by event id
docker compose logs -f service # one structured line per event- How each stage works (architecture and data flow) →
docs/DETAILS.md - Inspection commands (topic / DLQ / store) and component-by-component test recipes →
docs/MANUAL_TESTING.md
All configuration is via environment variables. Copy .env.example to .env and edit. .env is
gitignored; only .env.example is committed, and it holds no real secrets. Every variable has a
default in docker-compose.yml, so the stack starts without a .env. The exception is
ANTHROPIC_API_KEY, which has no default and is only needed when the reasoning worker runs.
| Variable | Default (dev) | Notes |
|---|---|---|
ANTHROPIC_API_KEY |
(none) | Secret. Attributes new events. Without it the worker skips reasoning (events stay pending) rather than failing; set it and restart to attribute the held backlog. Never commit it. |
ANTHROPIC_MODEL |
claude-opus-4-8 |
Model used for the risk brief. |
POSTGRES_USER |
quakes |
Dev credential. |
POSTGRES_PASSWORD |
quakes |
Dev credential. Not for production. |
POSTGRES_DB |
quakes |
|
DATABASE_URL |
postgresql://quakes:quakes@postgres:5432/quakes |
Used by the Python service. |
REDPANDA_BROKERS |
redpanda:9092 |
In-network address. Host tools use localhost:19092. |
QUAKES_TOPIC |
quakes.filtered |
Topic the worker consumes. |
CONSUMER_GROUP |
quake-reasoner |
Worker's Kafka consumer group. |
MAG_THRESHOLD |
2.5 |
Drop quakes below this magnitude (Connect filter). Lower it (e.g. 0.1) to see events flow. |
POLL_INTERVAL |
15m |
USGS poll cadence. all_hour carries each event for ~an hour, so 15m is plenty. |
USGS_FEED_URL |
…/summary/all_hour.geojson |
Feed the pipeline polls. |
USGS_USER_AGENT |
redpanda-takehome/0.1 (…) |
Sent on every fetch; USGS 403s without a User-Agent. |
REASON_MAG_THRESHOLD |
2.5 |
Worker routing: reason an event only if its mag ≥ this (or it's in a cluster); else skipped. Lower to 1.5 to reason smaller quakes. |
CLUSTER_RADIUS_KM / CLUSTER_DAYS / CLUSTER_MIN |
100 / 30 / 3 |
Nearby-cluster window used for routing and prompt context. |
REASON_MAX_TOKENS |
2048 |
Max output tokens per model call. |
REASON_MAX_ATTEMPTS |
3 |
Retries per call on transient Anthropic API errors. |
REASON_PARSE_ATTEMPTS |
2 |
Model call + repair attempts before falling back to unclassified. |
REASON_CONFIDENCE_THRESHOLD |
0.5 |
Below this, a valid brief is routed to needs_review. |
| Service | Host port | Purpose |
|---|---|---|
| Redpanda | 19092 |
Kafka API (external listener, for host tools) |
| Redpanda | 9644 |
Admin API |
| Redpanda Console | 8080 |
Web UI |
| Postgres | 5432 |
SQL |
| Serve (FastAPI) | 8000 |
Read-only briefs API + HTML index (GET /briefs, /briefs/{id}, /) |
One test guards the riskiest logic in the reasoning service: the dirty-output parse, the fallback,
and the confidence branch (service/test_reason.py). It runs offline with no API key, network,
or database (the Anthropic call and the nearby-events query are stubbed), so canned bad/edge model
outputs drive the parse → fallback → branch path directly.
cd service
uv pip install -r requirements.txt
uv run pytest -qIt asserts that unparseable model output degrades to a template brief at status='unclassified'
(never a crash or a null row), and that a valid but low-confidence brief routes to
status='needs_review'. To confirm the test actually guards that logic, break the fallback (e.g.
replace the _fallback() return in reason.py) and the fallback test goes red.
In the current implementation Connect is used to extract information from the USGS API, write it to a store (database), and make the data available on a Kafka topic for a worker to consume. This enables the worker to scale independently depending on the incoming load. Once the worker has completed the reasoning, the results are written back to the store. Meaning, the worker has SQL and write logic to the store.
In a way the current implementation is a hybrid between these two tradeoffs, since Connect currently writes to the sink directly (store) and the worker does as well. Storing the data as it arrives and performing a transform allows us to shape the data correctly for reasoning. You’ll notice that the store only contains data that is required for the reasoning. Depending on business requirements, it might be desirable to store the data exactly as it arrives and then perform another Connect for the transformation, but ultimately that is a business driven decision.
An alternative approach would be to have the worker write to a different Kafka topic and have Connect write it to the store.
The decision to shift from the current implementation to using Connect to write to the store would have a few driving forces:
- Code maintenance: currently the worker has a relationship and integration to the store; by using Connect the logic to write to the store would be offloaded to Connect, keeping the worker only responsible for the business logic.
- Scale: The USGS API isn't high throughput or anything like that, but if we are to imagine that a disaster occurred and we have a surge of records incoming, the worker could potentially overload the store. By writing the reasoning to Kafka instead, the writes to the database would have a consistent retry and backoff configuration.
- Reliability: If a worker crashes during a database write then you would have to do the reasoning again, which would incur additional charges. If the database is down or undergoing maintenance, you can still continue to write to Kafka and then Connect will pick up from where it left off.
- Multiple consumers: the current implementation assumes the store is the final destination for the reasoning data, but if we are to add additional checks, business logic, etc., we would have additional consumers of the data. Rather than sending all consumers to the store, they can consume from the Kafka topic directly.
- Additional data contract gate: prior to writing to the store you can validate that the data is in the correct shape, type, and structure by configuring a
json_schema. This isn’t to replace any data type checks in the worker but would be a way to adhere to the established data contract. Additionally, if the data contract remains inside the worker it could fail silently and you would have to review the worker's logs to understand the data, but by having it potentially error in Connect and sent to a DLQ you would have a record to troubleshoot against.
Shifting the write logic from the worker to Connect should be decided depending on business requirements, scale, and growth of the service. For example: adding additional consumers, growing the reasoning to multiple stages, or an increase in data rate—these would be the determining factors to shift the design. This shift comes with its own risks:
- Additional moving parts with managing an additional Connect pipeline and a topic
- Design shifts from a synchronous write to asynchronous and additional hops which could add time between a record arrival to having the quake brief ready.
- Currently, the store is a single table, but by having Connect write to the store the data model in the store would need to evolve to make it easier for Connect to write without risking overwriting existing data.
How you bound LLM cost/latency — filter in Connect first, batch in the service, or gate on confidence
In the current implementation, we have gates along the data flow to ensure that reasoning is optimal and not wasteful. The gates we have today:
- Filtering events in Connect. The mag/type filter drops whole events before they reach the worker, so no model call happens at all for a quake we don't care about. Additionally, Connect only hands the LLM the fields required to reason, so we aren't spending tokens on noise either. By doing this we reduce the number of requests (not just smaller prompts).
- Gating in the worker, before any requests are sent, the worker only reasons an event if the magnitude clears
REASON_MAG_THRESHOLDor the event is in an active nearby cluster. This is logic we can determine based on the data at hand. - Tagging briefs with the model's confidence value. In the case that a brief comes back below the threshold it's tagged with
needs_review. Today this is really a routing/quality mechanism.
Essentially, any reasoning that can be done by an if/else, or logic, should be codified, keeping the behavior deterministic. Anything that requires interpretation or a judgment call gets deferred to the appropriate model.
On the latency side, every event today is a synchronous per-event call (with adaptive thinking and retries on transient errors), so a brief lands within seconds of the quake. Any decision we make would shift this from real time to near real time to potentially a day.
The gap in the current implementation is that we need additional data to optimize on model selection. To do that we would need to store the model used, the brief generated, and version the prompt used. That way you can make an informed decision on which model gives you better confidence.
Each of the knobs, filter, batch and gate, has an impact on cost and latency. Ultimately, how quickly you want to see the brief from the time a quake occurs is what drives a different design.
For the knobs we are considering here, the alternatives are:
- Batching requests to the Anthropic API
- Finding additional data sources to spot check the confidence values of different models
- Model routing based on filtered data
For the first alternative, if we can assume we don't have any requirements around generating briefs in near real time. Said another way, if the business is okay to wait up to one day to see a brief, then we can leverage batching against the Anthropic API. By batching the requests we could gain cost savings of up to 50%, at the cost of trading the current seconds-to-brief latency for hours.
Currently the model itself provides a self-reported confidence value, which might be incorrect or misleading. Validating whether a quake is natural or induced against a third party data source or a subject matter expert (SME) would let us check the confidence metrics the model generates. This provides a feedback loop around the confidence value and lets us test against generic and more specialized models. Any additional third party data would follow the same established pattern of using Connect to grab and filter it, exposed as a typed field, rather than the worker fetching it at reason time.
Once we have those metrics and a clearer picture of the confidence levels we want, we can start to optimize with model routing. This would extend route() from a simple skip or reason into a skip and pick the right model size routing. The routing decision shouldn't be magnitude alone as there a multiple factors that feed into if it’s natural or induced. The straightforward, high-confidence cases go to a smaller, cheaper model, and the ambiguous or clustered ones go to the larger model.
The decision shift here is driven by:
- How quickly do you need to see the brief?
- Are you able to validate the reasoned briefs against third party data or an SME?
- What are the metrics for a brief across a specific model, prompt, and confidence?
This would then let us leverage the gathered metrics to optimize model routing.
Honestly, remembering from my Data Engineering days where I've had to write custom integrations to extract data, or had to use Airbyte, Fivetran, Stitch, etc., how much more flexible it is to use Connect. I always felt that unless you create your own integration, you are forced to use a UI to configure an integration, but with Connect I felt right at home with Infrastructure as Code. I'll need to spend more time on Bloblang to understand and learn it without relying entirely on AI, and for me to understand its limitations and best practices. For example, learning the difference between using a http_client as an input and a processor http when it comes to the body.
Having done work on data pipelines in the past, I realized how much overlap there is with an agentic workflow. Really, the ultimate goal is very similar, and it's to avoid: garbage in <-> garbage out. The bulk of the effort was still on curating the data, gathering the data and shaping the data for reasoning to consume it.
Assuming we are using a production grade Connect and Kafka with a worker that is able to scale to multiple instances, the focus of these recommendations is on the worker code and API serve:
- Worker:
- Currently, a worker opens a single connection to the database on startup, so if the database has any issues the worker would need to be restarted. Having the database connection in a wrapper to reconnect on failure would solve this.
- Single model provider with no backups. We can use the same model but hosted differently (AWS Bedrock, for example) or add support for a different provider as a backup.
- A failure caused by a bad message would crash the worker, and when it restarts it would crash again and again. This can be solved by writing the bad message to a DLQ for further inspection.
- Database:
- Currently, it's a single table. A data model with a few tables would be easier to scale and maintain, as you can optimize lookups for each table separately.
- Serve:
- The serve function is unauthenticated with no rate limits, which would make it susceptible to exploitation.
- Serve opens a brand-new database connection per request with no pool.
psycopg3does close the connection at the end of thewithblock, so it's not a leak, but under concurrency you still exhaustmax_connections(and pay the open/close churn), which starves the worker on the shared database. To fix this we can use a connection pool with a short-TTL cache.
Additional enhancements:
- Evaluating if Temporal is a good fit. Temporal can provide a state machine and audit logs out of the box, but it can be overkill for a workflow of one activity. As this product evolves and improves, Temporal would be helpful as a way to handle the data flow and resume from any failed states.
- This project already tests the values returned by reasoning to guard against returning malformed data. Connect, Worker and Serve are covered by the manual guide in
docs/MANUAL_TESTING.md. The enhancement is to promote that manual coverage into automated unit and integration tests that run in CI on every release going forward, so those three components are exercised automatically rather than by hand.
The system gives an environmental assessor or insurance provider an understanding of what caused an earthquake, whether it's natural, volcanic, induced-mining, induced-injection, induced-geothermal or uncertain. Rather than waiting for a specialist to review and classify each event, it delivers a quick first pass on all events, helping you make informed decisions faster. That cause can determine the level of compensation an impacted person receives, so labeling an event with the wrong cause could lead to an insurance overpayment or an incorrect environmental impact assessment. The system has a confidence check built in that needs to be factored into that decision, especially where a brief comes back as needs_review and a person should confirm it before money or liability is assigned.