yana-stocks: A Next.js Microservices Platform
An 11-service polyglot platform for real-time stock data, portfolios and ML predictions — service boundaries, layered caching, tracing, and change-aware CI.
Most of what I write about here is the on-prem cloud itself — the cluster, the GitOps, the shared plumbing. yana-stocks is the thing that actually runs on top of it: an 11-service platform for real-time stock prices, portfolio tracking, news sentiment, and ML-based price prediction, fronted by a Next.js dashboard at stocks.yanatech.co.uk.
This isn't a build log, and it isn't an exhaustive tour either — most of the system is deliberately boring, and cataloguing it section by section would read like internal documentation. Instead: a map of the whole shape first, then the parts of the design that carry the most weight — the SOLID service boundaries, the data-fetching and caching strategy, the asset and Core Web Vitals work, fault tolerance, external-API resilience and auth security, observability, and CI — described as they stand today and why they're built that way.
Eleven services and three languages is more than a stock-tracking app with no paying users needs. I built it this way on purpose — to work hands-on with the same patterns (event-driven services, polyglot boundaries, production observability) a larger team would use at scale. Read this as a portfolio piece demonstrating that, not as a sizing recommendation.
A second framing note, since the domain here is finance: I don't claim any particular expertise in financial modelling, trading, or markets. This is a software project that happens to use finance as its domain — real-time prices, sentiment, and predictions gave the frontend and backend something genuinely complex to build against — not a finance project that happens to use software. Treat FinBERT's scores and Prophet's forecasts as real, running code, not investment advice.
The Map
Eleven services in one Turborepo/pnpm monorepo, three languages chosen deliberately rather than by habit:
- Go for
auth-service— the one hot-path, latency-sensitive service where a fast static binary earns its keep - NestJS for everything else in the request path —
profile-service,portfolio-service,portfolio-api,price-processor - Python for anything touching the ML ecosystem —
price-ingestor,sentiment-analyzer(HuggingFace FinBERT),ml-predictor(Prophet) — because that's where the libraries live
Different languages, same shape underneath: every NestJS service is controller → service → repository, the Go one is handler → service → db, and packages/shared-types/shared-dto are the only contracts everything agrees on.
Kafka is the event backbone — every cross-service handoff that doesn't need a synchronous answer goes through it:
Every topic in that table earns its row — each one has both a real producer and a real consumer. That's a deliberate discipline, not an accident: an event stream nobody reads is a feature the diagram implies but the system doesn't have, so anything that doesn't clear that bar doesn't get to exist here.
Data ownership follows one rule — one service, one owner — with exactly one deliberate crossing, covered in full further down in "The News-Polling Budget: Sized to a Rate Limit, Not a Free-Tier Cap":
That's the internal shape — services, events, and who owns what. What decides who's allowed through the edge of it is next.
The Gateway: Kong Routing and Token Auth
At the edge, Kong handles JWT validation and CORS as gateway plugins rather than in-app middleware duplicated across five services. The routing table draws the public/protected line:
The auth lifecycle behind that table is short-lived HS256 access tokens with rotating opaque refresh tokens — a leaked-but-unused refresh token has a short shelf life because using it once invalidates it:
Password reset keeps the no-enumeration discipline a reset endpoint is supposed to have — POST /password/reset-request returns 200 whether or not the email exists, and only a real match gets a single-use, 1-hour Redis token. Registration is the one place auth-service talks to the rest of the system unprompted: it publishes users.registered so profile-service can create an initial profile without auth-service ever knowing profile-service exists.
Two more pieces sit on top of that lifecycle, both covered in full in "API Resilience and Security" further down. Kong's rate-limiting/rate-limiting-public plugins stack on this same routing table — 300/min on the JWT-protected routes, 60/min on the public ones, both IP-scoped. And the login/refresh exchange diagrammed above is called by the frontend's own BFF layer on the browser's behalf, not by browser JavaScript directly — what the browser itself holds is an httpOnly cookie, never the token.
The map so far is all internal. Here's the rest of it — everything that talks to the outside world.
Where the Data Actually Comes From
Five external services feed this system, each chosen for how its data actually behaves rather than by default — one push feed for US prices that never sleeps during market hours, two on-demand pull APIs for everything that doesn't fit that shape, one model host touched exactly once, and one service that only ever receives data rather than returning it. One of those five — Financial Modeling Prep's news feed — is rate-limited per minute rather than by a fixed daily count; the allocation algorithm built to respect that limit gets a section of its own further down.
Massive (Polygon.io) is the one push feed. price-ingestor opens a single WebSocket to Massive's starter feed and subscribes once per tracked symbol; after that there's no polling and, unlike FMP, no daily budget to ration — the feed pushes a new minute aggregate whenever one exists, and the service just republishes it to Kafka:
# main.py — subscribe to Massive's WebSocket feed for every tracked symbol
subscriptions = [f"AM.{s}" for s in settings.symbol_list]
client = WebSocketClient(
api_key=settings.massive_api_key,
feed=Feed.StarterFeed,
market=Market.Stocks,
)
client.subscribe(*subscriptions)
client.run(handle_msg) # blocks, auto-reconnects on disconnect
# one AM.<symbol> push becomes one bar published to Kafka
bar = RawPriceMessage(
symbol=msg.symbol,
open=float(msg.open), high=float(msg.high),
low=float(msg.low), close=float(msg.close),
volume=float(msg.volume),
timestamp=datetime.fromtimestamp(msg.start_timestamp / 1000, tz=UTC).isoformat(),
)
producer.publish(bar)
That's the SDK's parsed EquityAgg object, not a guessed raw WebSocket frame.
Financial Modeling Prep supplies news, on demand. The Starter plan rate-limits it at roughly 300 requests a minute, with no daily cap — why an allocation budget still exists despite that headroom is its own section below — one request per symbol per poll, and the pipeline keeps only what it needs from a much larger response:
# fmp_news_client.py
response = self._client.get(
"https://financialmodelingprep.com/stable/news/stock",
params={"symbols": symbol, "limit": 50, "from": from_date, "apikey": self._api_key},
)
// one article from the response — the four fields that survive into MongoDB
{
"title": "Fed holds rates steady, signals two cuts in 2027",
"site": "reuters.com",
"url": "https://www.reuters.com/markets/us/fed-holds-rates-2027",
"publishedDate": "2026-07-23 14:05:00"
}
Twelve Data covers what Massive doesn't: everything outside the US. The Grow plan rate-limits it per minute — a credit budget, not a daily cap — comfortably covering price-processor's on-demand .L-suffixed lookups and portfolio-api's 31-symbol FTSE 100 sector-rotation burst alike. A second on-demand provider rather than one feed trying to cover every market:
// twelve-data.service.ts — daily bars for an LSE symbol
const resp = await this.http.get<TwelveDataTimeSeries>('/time_series', {
params: {
symbol: this.tdSymbol(symbol), // 'BT' → 'BT.A' — a bare 'BT' 404s on this exchange
exchange: 'LSE',
interval: '1day',
outputsize: 730,
apikey: this.apiKey,
},
});
// one bar from `values[]`
{
"datetime": "2026-07-23",
"open": "412.30",
"high": "417.85",
"low": "410.10",
"close": "416.20",
"volume": "1834221"
}
FinBERT completes the picture from the model side — downloaded once, never called per request. sentiment-analyzer builds a local transformers pipeline on startup; the HuggingFace Hub is touched exactly once, to pull and cache ProsusAI/finbert's weights, and every inference after that runs against the local model with no further network round trip:
# analyzer.py — downloads ProsusAI/finbert once, then infers locally
self._pipe = _hf_pipeline("text-classification", model=model_name, top_k=None)
# one FMP headline in, a 3-class softmax out
raw = self._pipe(text[:512])
// the raw pipeline output for one headline — all three classes, before collapsing to a stored score
[
{ "label": "positive", "score": 0.0421 },
{ "label": "negative", "score": 0.8737 },
{ "label": "neutral", "score": 0.0842 }
]
The service folds that into positive − negative, a single signed score in [-1, 1] — the wider raw shape above exists mainly to make the "downloaded once, inferred locally" point concrete: nothing here ever goes back out to HuggingFace. Why FinBERT specifically, rather than a general-purpose sentiment model, is covered further down alongside the rest of the ML pipeline story.
Sentry is the fifth dependency, and the odd one out — data flows out, not in. Every service initialises it the same way, error-capture only; tracing itself stays on OpenTelemetry, covered separately in "One trace_id Across Three Languages" below:
// sentry.server.config.ts
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
environment: process.env.NODE_ENV,
tracesSampleRate: 0,
});
What leaves the system on a captured exception is the error message, stack trace, and an environment tag — and, because SentrySpanProcessor bridges the two, the active trace_id, so an error in Sentry's dashboard links back to the same trace Tempo already has for it.
That's the five: two market-data feeds (one push, one on-demand), one on-demand news/ratings API, one model host, and one outward-only error tracker — each shown here with the real call and, save for Sentry, the real shape of what actually comes back.
That's the map. Now the parts that carry the design weight.
The News-Polling Budget: Sized to a Rate Limit, Not a Free-Tier Cap
Financial Modeling Prep's Starter plan — introduced above — rate-limits at roughly 300 requests a minute, with no fixed daily cap. Nothing forces a symbol to be dropped today. The allocation algorithm stays anyway: sentiment-analyzer's tracked universe — the baseline plus whatever any user holds, watches, or searches for — has no upper bound of its own, and a per-minute limit is still a real ceiling somewhere out past today's numbers. Keeping the allocation code, just re-sized to the real limit instead of removed, is cheaper than deleting it and rediscovering that ceiling under load later.
Symbols any user actually holds or watches get fetched fresh every cycle — a user's own portfolio never goes stale for lack of budget. Whatever budget remains after that (a fixed max_symbols_per_poll, currently 50 — comfortably above the ~30-ticker baseline) covers that baseline in one pass on most cycles; the rotation below only actually kicks in once held/watched symbols, or the baseline itself, grow enough to eat into that headroom:
The property that matters: requests in any single poll can't exceed the budget by construction, no matter how large the tracked universe grows — the universe growing just means the baseline rotation takes more cycles to come back around, while held symbols stay fresh regardless.
This is also the one place the data-ownership rule gets deliberately crossed. To know which symbols matter, sentiment-analyzer reads portfolio-service's portfolios and watchlists collections directly — same physical MongoDB, another service's collections. ml-predictor reads the same union of symbols but skips the rotation entirely, for a reason worth being precise about: training reads its own already-collected price history out of price-processor's collection, not a rate-limited external API, so the only cost is compute and there's nothing to ration.
Since the two ML services are on the table — what they actually run, briefly, because it's the part a CRUD tour would skip:
FinBERT is BERT fine-tuned on financial text — 10-Ks, analyst notes, financial news — and the fine-tuning corpus is the whole point. "Shares tumbled" or "guidance cut" read as strongly negative to anyone who follows markets; a general-purpose sentiment model trained mostly on product and movie reviews has no reason to have learned that. (The pipeline call itself, and the raw three-class output it returns, are shown earlier in "Where the Data Actually Comes From" — it's a one-time model download, not a per-request API.)
Prophet earns its place for the opposite reason — not sophistication, but fit-and-forget operability. It models price as additive decomposition (trend + seasonality + holiday) rather than a learned recurrence, which makes it tolerant of missing bars and outliers and cheap to fit unattended. That's exactly this job's shape: dozens of small per-symbol models refit hourly, not one large model that would need careful tuning to serve every symbol at once. Each fit produces a forecast with an uncertainty interval, the artifact goes to MinIO, and the forecast is published for portfolio-api to aggregate.
SOLID, Made Concrete
The layering rule from the map — controller → service → repository in every NestJS service — isn't a style preference; it's where the SOLID principles stop being poster material and start deciding where code goes.
Single responsibility, at two scales. Per service: profile-service only ever touches non-PII display data, portfolio-service only ever touches portfolios, watchlists, and trades — there's no shared codebase for scope creep to hide in. Per layer: a controller owns HTTP concerns (routing, guards, validation), a service owns the business rules, a repository owns persistence, and none of them reaches around the next.
Dependency inversion runs through NestJS's constructor injection — a controller depends on a service, which depends on repositories, never on Mongoose directly. The real portfolio-service add-stock path, trimmed to its shape:
// portfolios.controller.ts — HTTP concerns only: route, guard, validation
@Controller('portfolios')
@UseGuards(UserFromTokenGuard)
export class PortfoliosController {
constructor(private readonly portfoliosService: PortfoliosService) {}
@Post(':id/stocks')
addStock(@Param('id') id: string, @Body(ValidationPipe) dto: AddStockDto) {
return this.portfoliosService.addStock(id, dto);
}
}
// portfolios.service.ts — business rules; no Mongoose in sight
@Injectable()
export class PortfoliosService {
constructor(
private readonly repo: PortfolioRepository,
private readonly tradeRepo: TradeRepository,
) {}
async addStock(id: string, dto: AddStockDto): Promise<Portfolio> {
const doc = await this.repo.findByIdForMutation(id);
if (!doc) throw new NotFoundException('Portfolio not found');
// …average the cost basis, seed latestPrice with the trade price…
const saved = await doc.save();
await this.tradeRepo.record({ portfolioId: id, type: 'buy', ...dto });
return this.toResponse(saved);
}
}
Swapping how PortfolioRepository persists data never touches the controller — and the unit specs exploit exactly that seam: every repository is substituted with a Jest mock satisfying the same surface, which is Liskov substitution doing practical work rather than sitting in a textbook.
Interface segregation lives in the shared packages: packages/shared-types and packages/shared-dto are the only contracts every service and the frontend agree on (Portfolio, Trade, AddStockDto), each scoped to what its consumers actually use rather than one god-object of every field any service has ever needed. And open/closed shows up most visibly at the system boundary: new consumers attach to existing Kafka topics without the producer changing a line — profile-service exists by subscribing to users.registered, and auth-service neither knows nor cares.
Data-Fetching: Where SSR, SSG, and ISR Each Land
All three rendering strategies got a deliberate decision here, and only one of them is "on" in the obvious sense.
SSG is deliberately off. Every route is forced dynamic — one export const dynamic = 'force-dynamic' in the root layout, cascading to every page — for two stacked reasons: the CSP's script-src needs a per-request nonce that only a dynamic render can carry (its own section below), and the root layout's Navbar/Providers/CookieBanner are client components that hydrate on every route anyway, so no page could safely be left as build-time static HTML.
SSR is real, not incidental. The homepage is an async Server Component that fetches its above-the-fold public endpoints (market/overview, market/movers, market/factors, market/sectors/rotation) on the server, so the initial HTML carries real market data rather than a loading skeleton — confirmed by curling the production build with JavaScript disabled and finding the numbers already in the response.
ISR survives at the data layer. force-dynamic disables static generation, not data caching: those server-side fetches use fetch(..., { next: { revalidate } }), which lands in Next's Data Cache — shared across requests and refreshed in the background on an interval, which is exactly ISR's semantics, applied to data instead of whole pages. Every user's homepage render shares one cached fetch per endpoint instead of fanning out to the backend.
The server-to-client handoff is where the sharp edge lives: the fetched data hydrates a per-request QueryClient via dehydrate/HydrationBoundary, so TanStack Query picks up on the client exactly where the server left off. Per-request matters — the client-side singleton QueryClient is one instance per Node process, and prefetching into it would leak one user's response into the next request that hits the same server instance.
Caching: A Hierarchy of Deliberate TTLs
Scalability here isn't one cache — it's a stack of them, each sized to the load it absorbs, with the TTL as an explicit staleness budget:
There's no single aggregate cache on portfolio-api — it composes /stocks/:symbol from separately-cached values, each on its own TTL. A /market/movers cache runs 10 seconds, matched to how often that endpoint is actually hit. Sentiment and prediction are populated straight off their Kafka consumers rather than fetched on read, and cached for 24 and 48 hours respectively — those signals only change on each model's own refresh cycle (a news poll, an hourly Prophet refit), not per request, so there's nothing to gain from a shorter window. A 15-minute price fallback cache covers symbols the streaming pipeline hasn't priced yet. price-processor's 5-second price:latest:<symbol> cache is the other big one, keeping hot quote reads off MongoDB between minute bars — prices tick per minute, so 5 seconds is invisible to a user while flattening read load, and a longer TTL would buy nothing but staleness.
Just as deliberate is what's shared versus what isn't. The Next Data Cache is shared across all users because it only ever holds public market data; anything user-specific stays in the per-request QueryClient and per-user API calls. A cache is also a data-leak vector the moment that line blurs — the same reason the singleton-QueryClient trap in the previous section matters.
The last row isn't a runtime cache at all: BuildKit's registry-backed layer cache (a per-service :buildcache tag in Harbor) and the self-hosted, MinIO-backed Turborepo remote cache make CI cost proportional to what actually changed — the same principle as the change-aware pipeline below, applied to build artifacts instead of requests.
Asset Optimisation: A Chart Bundle That Only Ships When There's Data
The heaviest thing the homepage can load is SectorRotationHeatmap's treemap view: recharts plus its dependency tree — d3-scale, d3-shape, redux-toolkit, immer. It's also worthless on an empty state — no sector data, no treemap — so the page is wired so that none of those bytes ship unless the treemap will actually render.
That wiring takes two pieces working together, and both are load-bearing. The emptiness check lives in the parent component, which decides whether to mount the treemap at all; the treemap itself is imported via next/dynamic(..., { ssr: false }). Neither piece works alone — next/dynamic's default is ssr: true, and under that default the server emits the chunk's <script> tag on every render whether or not the branch that mounts the component executes, because the server can't statically know a client-side conditional won't take it:
Verified the blunt way: a standalone production server with no backend, curl the homepage HTML, grep for the recharts chunk — zero matches, and zero network requests for it even after full hydration. The trade-off is accepted deliberately: when there is real sector data, the treemap costs a client-side round-trip instead of painting synchronously in the SSR HTML like the rest of the homepage. The same discipline applies below the fold: MarketBrowser and StockScreener — the tabbed section where only one is ever visible — are next/dynamic imports too, keeping their JavaScript out of the homepage's main bundle.
Keeping it this way is Lighthouse's job, in CI rather than by hand: @lhci/cli runs three passes against a real next start production build on every push, asserting numeric budgets on the Core Web Vitals (performance ≥ 0.8, LCP ≤ 2500ms, CLS ≤ 0.1, TBT ≤ 300ms) — warn-level for now, deliberately, until there's enough run history to separate real regressions from noise on a shared runner. Reports upload to a self-hosted LHCI server rather than Google's temporary-public-storage, and the deciding factor was narrow: only the lhci and temporary-public-storage targets can post a GitHub commit status at all (confirmed by reading @lhci/cli's own source, not assumed), and the public option puts every full HTML report on an unauthenticated Google-hosted URL. The server sits behind HTTP Basic Auth instead of the cluster's usual Authentik SSO because it has to serve both CI's unattended upload and a human clicking the commit-status link — an SSO redirect flow doesn't cleanly survive the first one.
Current production numbers, pulled from the self-hosted LHCI server rather than eyeballed off a single run: 97 performance, 100 across accessibility, best practices, and SEO, with the Core Web Vitals still comfortably in Lighthouse's green band — LCP at 1.0s, TBT at 15ms, CLS at 0.08. The homepage's two-column row (SectorRotationHeatmap and MarketNews) still reserves the same explicit height on both sides regardless of loading or data state, which is what keeps CLS this low in the first place; it no longer measures a flat zero the way it did right after that fix landed, and the small residual shift hasn't been traced to a specific element yet — noted here rather than quietly rounded away.
Best Practices now sits at a clean 100, not the 96 it held for a while. The gap back then was a single audit: an intermittent hydration-mismatch console error (Minified React error #418) that surfaced specifically on Lighthouse's own repeated passes against this page — investigated at length (live data ticking, the treemap's dynamic import, and the Data Cache were each ruled out with direct evidence) and isolated to something specific to Lighthouse's own Chrome instance across repeated runs, not a real user-facing issue. It hasn't reproduced across the last three CI runs, which is what closed the gap. The production bundle still deliberately ships without public source maps — Sentry gets private ones instead via widenClientFileUpload — but that particular audit carries zero weight in Lighthouse's own Best Practices scoring, so it was never actually the thing costing points; framing it as a second reason for the old 96 overstated its effect.
CI only ever points Lighthouse at the public, unauthenticated homepage — the dashboard behind login isn't part of that automated run at all. A manual DevTools Lighthouse pass against the authenticated /dashboard route turned up a real, separate accessibility violation: a portfolio card's name rendered as an <h3> directly under the page's <h1>, skipping heading level 2 entirely — the kind of gap that only ever fails a heading-order check, not a visual review, since screen reader users are the ones who navigate a page by its heading tree. Bumping that one element to <h2> was the whole fix; re-running Lighthouse against production afterward, with the fix confirmed live by the deployed pod's image tag matching the fixing commit, showed a clean 100 across all four categories on that page too — FCP 0.2s, LCP 0.7s, TBT 0ms, CLS 0.002, Speed Index 0.2s, every metric tighter than the homepage's own numbers above.
A Real CSP on a Fully-Dynamic Dashboard
The site ships with a strict Content-Security-Policy — the browser-enforced allowlist deciding what the page may load, run, and connect to. On a client-heavy dashboard that means a nonce-based script-src with 'strict-dynamic': a fresh nonce generated per request, which Next applies to its own inline hydration scripts. Here's how that's actually wired.
Where it lives. The header is built in src/proxy.ts — under this app's src/app/ layout convention, that's the only location Next.js picks a proxy file up from (a root-level proxy.ts is silently ignored: no build error, no middleware line in next build's route table, no header). The non-per-request security headers — X-Content-Type-Options, X-Frame-Options, Referrer-Policy, Permissions-Policy — stay in next.config.mjs's static headers(), since they don't need a request-time value.
Why every route is dynamic. A per-request nonce can only exist on a dynamic render — a statically prerendered page's <script> tags are baked at build time, before proxy.ts ever runs, so they'd carry no nonce and be blocked in production (and only in production: pnpm dev renders every request fresh, so the mismatch never shows there). So the root layout exports dynamic = 'force-dynamic' once, cascading to every route — which also matches reality, since the layout's Navbar/Providers/CookieBanner are client components that hydrate on every route anyway:
What forcing dynamic does — and deliberately doesn't — cost is the data-fetching section above: static generation is off, but SSR still puts real data in the initial HTML and the Data Cache still delivers ISR semantics at the data layer.
The directives that carry real decisions. img-src allows https: broadly rather than a host allowlist, because profile-service's avatar field is a free-form user-supplied URL — a fixed host list would reject a real fraction of valid avatars. connect-src is just 'self' plus Sentry's ingest host — the browser never calls a backend origin directly at all: every request leaves through the frontend's own /api/* proxy (the BFF, covered in "API Resilience and Security" further down), so there's no second origin for the policy to allow, and the same policy is correct in every environment with nothing to compute at request time. The Sentry entry is region-specific (*.ingest.de.sentry.io for this project's EU DSN) — the region matters, because a generic or wrong-region entry blocks every error report at the CSP layer with no symptom beyond a quiet gap in Sentry's dashboard.
Two other apps in this workspace shipped a nonce-less static CSP, broke hydration in production, and had to be fixed after the fact. yana-stocks never shipped without one — the CSP was part of the first version, designed around these constraints from the start rather than retrofitted after an incident.
One trace_id Across Three Languages
The payoff first, because it's the reason any of this exists: a slow GET /stocks/:symbol that's waiting on ml-predictor renders in Tempo as one continuous span tree — the trace itself points at the bottleneck service. A Kafka hop stays in the same trace too: the traceparent travels inside the message, so the consumer's span continues the producer's trace even though it may run long after the producer returned — one trace_id from a Python producer to its Node consumer, one value to paste into Loki and see both services' logs, instead of correlating timestamps and message fields by hand.
There is no single OTel SDK spanning Node, Go, and Python, so this is three independent implementations of the same protocol — NodeSDK with auto-instrumentation for the NestJS services and the Next server, otelhttp + otlptracehttp for Go, opentelemetry-sdk for Python — all exporting OTLP to a self-hosted Tempo.
Propagation is where the design carries the most weight, because Sentry is also in every service and Sentry has opinions. Trace continuity across a language boundary depends on the propagator, not on both sides being instrumented: Sentry's propagator alone only speaks its own sentry-trace/baggage headers, so the standard W3C traceparent header has to travel too for a trace to survive a boundary. On the NestJS side that's SentryPropagator with propagateTraceparent: true; on the Go and Python sides it's a composite propagator that keeps the standard TraceContext/Baggage propagators alongside Sentry's rather than replacing them. Each service also keeps Sentry from double-instrumenting: tracesSampleRate: 0 / skipOpenTelemetrySetup: true in Node, traces_sample_rate: 0 in Python, no OTLP exporter to Sentry in Go — Sentry does errors, OpenTelemetry stays the only tracer feeding Tempo.
Kafka propagation has one asymmetry worth naming: the Python services are producers only, so they're instrumented on the injection side alone; the NestJS consumers get extraction from auto-instrumentations-node's bundled kafkajs support; and auth-service's segmentio/kafka-go has no official OTel package at all, so that hop carries a small hand-rolled span and header injection. Every service flushes pending spans on SIGTERM, ahead of Kubernetes's SIGKILL, so the last in-flight batch survives pod termination.
The other three pillars get one paragraph, because they're solved problems executed carefully rather than problems: logs are structured JSON everywhere (Nest LoggerService adapter, Go's slog.JSONHandler, python-json-logger), shipped via Promtail to Loki, with trace_id/span_id stamped on any line written while a span is active — so a slow span and its log lines share a searchable value. Metrics split into business numbers (a Grafana dashboard querying auth-service's Postgres directly — no counter to instrument for what a SQL query already answers) and per-service /metrics endpoints scraped by kube-prometheus-stack via ServiceMonitors. Errors go to Sentry across all runtimes, DSNs from runtime k8s secrets — except the frontend's, baked in at build time via CI build-arg because NEXT_PUBLIC_* values must exist before the bundle compiles. None of the four pillars does another's job, and OTel as the shared instrumentation layer means swapping Tempo out later is a config change, not a rewrite.
Fault Tolerance: Built to Degrade, Not to Fall Over
An 11-service system has eleven ways to be partially down, so the design treats partial failure as the normal case and answers it layer by layer.
Redelivery is safe by construction. price-processor's transform is idempotent: each raw bar is upserted keyed on (symbol, timestamp, interval) with $setOnInsert, so a redelivered Kafka message — consumer restart, rebalance, a crash between processing and offset commit — can never create a duplicate bar. Idempotency is the cheapest form of fault tolerance there is: it makes at-least-once delivery indistinguishable from exactly-once for this workload, with no distributed-transaction machinery.
Missing data degrades; it doesn't error. A portfolio's valuation multiplies shares by latestPrice, which only exists once the price pipeline has streamed a tick for that symbol — so portfolio-service falls back to the holding's cost basis whenever no live price has arrived (market closed, pipeline down, fresh deploy). The dashboard shows a slightly conservative valuation instead of $0.00 or a 500.
Connections assume they'll drop. price-ingestor holds one WebSocket to the market feed and carries no state beyond the open socket — the client auto-reconnects on disconnect, and a pod restart just picks the stream back up, because there's nothing to recover. Every service also flushes pending OTel spans on SIGTERM, ahead of Kubernetes's SIGKILL — shutdown is an expected event, not an exception.
Replication covers the infrastructure layer. MongoDB runs as a replica set, auth-service's CNPG cluster keeps a primary plus a replica — which is also what lets node drains and automated reboots proceed, since a single-instance Postgres would pin its node behind a zero-disruption budget — and every HTTP-serving service keeps minReplicaCount: 1 under KEDA, so autoscaling can never scale a synchronous dependency down to zero.
Autoscaling is shaped to the workload, not applied uniformly. price-ingestor runs as a fixed single replica with no autoscaler at all — a pure Kafka producer with no consumer lag of its own to trigger one. Of the five services that do use KEDA, sentiment-analyzer is the one allowed to scale to zero (minReplicaCount: 0) — it's a background consumer with nothing synchronous depending on it staying up. The other four (price-processor, profile-service, portfolio-service, portfolio-api) all answer HTTP traffic directly, so each keeps the minReplicaCount: 1 floor described above.
Deploys are the failure mode with a seatbelt. ml-predictor skips KEDA's autoscaling entirely, because what varies for that service isn't load — it's model version, and the deployment strategy should match the thing that actually changes. Its canary doesn't just walk traffic 10% → 50% → 100% — the pause between steps runs an Argo Rollouts analysis, a Prometheus readiness query sampled every 30 seconds, and a fourth failed sample aborts the rollout. A bad model version stops at 10% and traffic snaps back to the stable version, with nobody rolling anything back by hand.
Two production edge cases, asked the way an on-call engineer would:
- What happens if
price-processordrops off Kafka during high volatility? Nothing is lost and nothing needs re-sending. Bars keep accumulating instocks.prices.raw(24-hour retention — far longer than any realistic outage), and the consumer group's committed offset lives broker-side, so the service resumes exactly where it left off. The backlog is also the recovery signal: KEDA reads the same consumer lag and scalesprice-processortoward its 3 replicas — one per partition — to burn it down, while the consumer's own supervision loop (recreate and reconnect with backoff on any start failure) means rejoining never needs a human. - How are consumer offsets handled — what does a crash mid-message mean? Offsets are committed after processing, a deliberate at-least-once choice: crash between the upsert and the offset commit, and the bar is redelivered rather than silently dropped. That's precisely why the transform is idempotent — a replayed bar hits the same
(symbol, timestamp, interval)key and changes nothing, so at-least-once delivery plus idempotency behaves like exactly-once without any transaction machinery. AndfromBeginning: falsemeans a fresh consumer group starts from the live edge instead of replaying a day of history it never promised to process.
API Resilience and Security: Circuit Breakers, Rate Limits, Idempotency, and a Cookie-Based BFF
The fault tolerance above is internal — Kafka redelivery, replication, autoscaling. One layer further out, the same discipline applies to everything the system depends on or exposes: every outbound call to a third party is metered and can fail closed, the edge enforces its own request budget independent of any single service, mutations can be retried safely without double-applying them, and the browser never holds anything more than an opaque, unreadable cookie.
Circuit breakers wrap every outbound call, one per provider. portfolio-api and price-processor wrap every FMP/Massive/Twelve Data call in an opossum breaker; sentiment-analyzer's single FMP news call site gets the Python equivalent, pybreaker. The breaker sits per provider, not per call site — stocks.service.ts and analyst.service.ts both funnel their FMP calls through the same fmp breaker, because a breaker needs many calls across its rolling window to accumulate a trip decision, and splitting that window per call site would mean each one trips on evidence the others can't see:
// external-api-breakers.service.ts — one CircuitBreaker per provider, shared across every call site
export type ExternalApiProvider = 'fmp' | 'massive' | 'twelvedata';
const BREAKER_OPTIONS = {
// No `timeout` here — each call site already sets its own axios timeout
// (3s-10s depending on urgency); racing a second one here would just shadow it.
errorThresholdPercentage: 50,
resetTimeout: 30_000,
rollingCountTimeout: 10_000,
};
fire<T>(provider: ExternalApiProvider, fn: () => Promise<T>): Promise<T> {
return this.getBreaker(provider).fire(fn) as Promise<T>;
}
Breaker events double as the failure metric — no separate instrumentation layer needed:
breaker.on('open', () => externalApiCircuitState.set({ provider }, 1)); // failing fast
breaker.on('halfOpen',() => externalApiCircuitState.set({ provider }, 0.5)); // one probe allowed
breaker.on('close', () => externalApiCircuitState.set({ provider }, 0)); // healthy
external_api_requests_total{provider,outcome} and external_api_circuit_state{provider} use identical names across both languages, so one ExternalApiCircuitOpen PrometheusRule in k8s-apps covers all three providers regardless of which service is calling them. FMP's news response and Polygon's aggregates envelope are also shape-validated at the same boundary (class-validator/class-transformer on the Node side, a small Pydantic model on the Python side) — a field a provider silently renames or retypes now falls through the same fallback path a network error already takes, counted as invalid_shape, instead of resolving quietly to undefined or an empty array.
Rate limiting lives at the edge, not in app code. Two Kong rate-limiting plugins stack on the routing table from "The Gateway" above — rate-limiting-public at 60/min on the CORS-only routes, rate-limiting at 300/min on the JWT-protected ones, both IP-scoped (no per-end-user KongConsumer registry exists here; the one KongConsumer in this stack is auth-service itself, for JWT issuance). Both run policy: redis against the cluster's shared Redis rather than Kong's other two options: cluster needs Kong's own Postgres, unavailable on this DB-less deployment, and local counts per-Kong-replica independently — so the effective limit would silently scale up with every extra replica instead of staying at the number in the config.
An opt-in Idempotency-Key covers unsafe retries; a batch endpoint covers unsafe fan-out. portfolio-api's mutating proxy routes (addStock, addStocksBatch, addWatchlistSymbol, createWatchlist) accept an optional Idempotency-Key header — a request with no header behaves like a normal, non-idempotent call. The interceptor hashes the request body against a Redis-stored key (papi:idem:<jwt sub>:<method>:<path>:<key>): the same key with the same body inside a 24-hour window replays the original {status, body} verbatim with an Idempotent-Replay: true header, without re-running the handler; the same key with a different body is a client bug and gets a 422; a key that's still mid-flight gets a 409 rather than racing the first attempt:
// idempotency.interceptor.ts — replay, reject, or race-guard, keyed on a hash of the body
if (!existing || existing.bodyHash !== bodyHash) {
throw new UnprocessableEntityException('Idempotency-Key was already used with a different request body');
}
if (existing.state === 'in_flight') {
throw new ConflictException('A request with this Idempotency-Key is already in progress');
}
res.setHeader('Idempotent-Replay', 'true');
portfolio-service has no Redis of its own — Mongo only — which is why this lives in portfolio-api's proxy layer instead of the service it's proxying to. The companion POST /portfolios/:id/stocks/batch (up to 50 holdings in one call) shares addStock's exact underlying logic and is deliberately not transactional, consistent with the single-item add path — docker-compose.yml's mongo:8 runs standalone with no replica set, so a session would fail in dev/CI regardless, and a batch that's honest about not being atomic beats one that only pretends to be.
This system deliberately doesn't use async-request-reply (202 Accepted plus a polling Location) for slow work: nothing here blocks a caller on a long-running operation — ensureTracking's instant-tracking calls, covered above, are already fire-and-forget, and the frontend already polls /stocks/:symbol every 10 seconds — so a job store would solve a problem the system doesn't have.
Auth tokens live in an httpOnly cookie, never in reach of JavaScript. The token itself isn't readable by any script on the page, so an XSS bug has nothing to exfiltrate. Every backend service independently trusts a Bearer token read straight off the request, with no cookie-awareness anywhere upstream, and Kong's jwt plugin has no facility to re-attach a cookie-extracted token as an Authorization header for the services behind it — so the frontend itself is a thin BFF (Backend-for-Frontend): the browser only ever calls its own origin, and one route — src/app/api/[...path]/route.ts — is the only piece of the system that ever sees the cookie.
The cookies themselves: access_token (Path=/, 15-minute maxAge matching auth-service's own JWT expiry) and refresh_token (Path=/api, 7 days) — both httpOnly, Secure in production, SameSite=Lax, and host-only with no Domain attribute, so they're scoped to stocks.yanatech.co.uk alone and never shared with any other *.yanatech.co.uk subdomain in this cluster.
// route.ts — the only place in the frontend that ever reads the cookie
const cookieStore = await cookies();
const accessToken = cookieStore.get(ACCESS_TOKEN_COOKIE)?.value;
const firstRes = await attempt(accessToken);
if (firstRes.status !== 401) return buildResponse(firstRes);
// Access token missing/expired — refresh once, retry once, invisible to the client.
const refreshToken = cookieStore.get(REFRESH_TOKEN_COOKIE)?.value;
const tokens = refreshToken ? await refreshOnce(refreshToken) : null;
The 401-refresh-retry above is transparent to the client by design, and refreshOnce exists because the refresh token is single-use and rotated server-side: a page firing several requests that all 401 at the same moment would otherwise send several refresh attempts against the same token, the first rotating it and every other one hard-failing a session that was actually still valid. It dedupes concurrent refreshes for the same token via an in-process Map, plus a short "recently rotated" cache so a request that read the cookie a moment before an earlier response's Set-Cookie updated it still resolves correctly instead of being treated as reusing a dead token. That cache is per-replica — a non-issue today since the frontend runs as a fixed-replica Deployment, and if it ever doesn't, the failure mode is a spurious re-login, not a correctness bug.
lib/api.ts and AuthContext.tsx carry no token-handling logic of their own — no client-side token storage, no client-side retry-on-401, since the BFF already handles both server-side. isAuthenticated is derived by calling GET /api/auth/me on mount (200 vs 401) rather than checking for a locally-held token. proxy.ts checks for access_token's presence before any protected route renders, including /stocks/[symbol] — a UX optimization only, since real enforcement is still Kong's signature check plus each service's own guard.
CSRF is covered by two layers, since cookies auto-attach on every request in a way a bearer token in JS never would: SameSite=Lax is the primary defense, and the proxy additionally rejects (403) any non-GET/HEAD request whose Origin header is present and doesn't match its own origin.
Kong, auth-service, and every other backend service are unaware any of this exists — each independently trusts a Bearer token read straight off the request, and the auth lifecycle diagrammed in "The Gateway" above is exactly what runs underneath, just invoked by the frontend's own server rather than by browser JavaScript. It's a deliberately reusable shape for any app on this stack with the same gateway-plus-independently-trusting-services topology: token custody stays at the edge closest to the browser, rather than teaching every downstream service a new trust model.
CI That Only Builds What Changed
Ten independently-buildable services share one repo and one workflow, and the change-set is data, not configuration: dorny/paths-filter checks which of ten tracked service paths actually changed, and a second step turns that directly into the Docker build matrix as JSON. Nothing downstream carries a service list to keep in sync — no per-service workflows with hardcoded path lists to drift, and no building all ten images on every push either. (A manual workflow_dispatch run defaults build_all to true, which is why a manual run rebuilds everything.)
Every job runs on runners-yana-stocks, a self-hosted ARC scale set — not by preference but by necessity: harbor.yanatech.co.uk isn't publicly resolvable, so a GitHub-hosted runner couldn't push an image even if everything else worked.
Three gate decisions carry the design weight. First, the two security scans — gitleaks over full git history, Trivy filesystem scan for dependency CVEs and IaC misconfiguration — start immediately, unconditionally, and everything else waits on both; they are not skippable by any path filter. Second, docker's gate is asymmetric on purpose: the security scans must be exactly success, while every quality job may be success or skipped — because a quality job legitimately skips when its area didn't change, and a skip there isn't a failure. Third, a second Trivy pass scans the built image (CRITICAL only) — deliberately different from the earlier filesystem scan, because a base image or the build process itself can introduce what a lockfile-level scan never sees.
gitops closes the loop: it checks out k8s-apps with its own PAT and, for each service actually built, uses yq to patch just the image field — on a Deployment for everything except ml-predictor, whose Argo Rollout gets patched instead, since that's the canary service. The yq expression is scoped with select(.kind == "Deployment" or .kind == "Rollout") specifically so it can never touch the Service definition sharing the same multi-document YAML file. It commits, pushes, and ArgoCD does the rest.
All of that GitOps weight is for the shared cluster; locally none of it applies. docker compose up -d (Redpanda standing in for Kafka, plus Postgres, MongoDB, Redis, MinIO) and pnpm dev cover the whole workspace — no Tilt, no devcontainers, and nothing self-hosted to reach first.
What's Tested — and What Isn't
Three layers, each testing a different thing. The table lists what's covered; the prose after it explains what the numbers mean.
Coverage is gated per-service against its own threshold rather than one shared bar — real numbers run from auth-service's 15% to portfolio-api's 87%, and a single global percentage would either be meaningless at the top or fail the bottom outright. The mechanism differs by language (Jest coverageThreshold, pytest-cov's fail_under, and for Go — which has no built-in equivalent — go tool cover piped through an awk comparison). Bootstrap and observability wiring are excluded from the count deliberately: Sentry init, OTel setup, the logger, /metrics, health checks — none of it has logic to test, and counting it would only inflate the number without saying anything about the code that matters. The frontend has no coverage config at all — a real gap, stated as one.
A separate e2e.yml, workflow_dispatch-only, runs the same Playwright suite against an arbitrary base_url — the actual "check staging before prod" step, and deliberately not automatic.
The open-items list, in one place: auth-service's untested crypto internals, profile-service's fake integration suite, and the frontend's missing coverage gate.
Closing
None of the individual pieces are exotic — Kafka, Kong, KEDA, OpenTelemetry, circuit breakers, and Next.js's own caching primitives are all well-documented, widely-used tools. What makes yana-stocks feel production-shaped isn't any one of them. It's that the boundaries hold all the way down — one service, one responsibility, one data owner, with the single deliberate exception called out where it happens — and that the load-bearing decisions above are part of the design itself rather than patches added afterward. The gaps are part of the same discipline: a system whose limitations are stated plainly, 15% coverage included, is a system you actually understand.