← Back to résumé

Design Patterns

Patterns applied in production systems — the constraint that forced each one, how it was implemented, and where the code lives.

Ordered problem-first, because a pattern without its motivating constraint is a textbook recital. Source references point into private repositories, so they are citations rather than links.

Architectural

Publish/Subscribe over a typed bus

Problem

Strategy evaluation ran once per subscriber. The same indicator math executed N times over identical market data, and there was no single place where a trading signal existed as a fact — nothing to audit, and no way to fan one decision out to several accounts.

Applied

Producers publish an immutable signal to a bus and never reference consumers. The bus is declared as a Protocol with an in-process implementation and a Redis implementation selected by environment variable, so moving from one process to many is configuration rather than redesign.

Evidence
  • signal-to-alpha · backend/app/v2/shared/bus.pySignalBus Protocol (:29), InProcessBus (:58), RedisBus (:128), make_bus() factory (:148), Subscription handle (:42)
  • signal-to-alpha · backend/app/v2/distributor/distributor.py:69Distributor fans one immutable signal to N subscribers

Strangler Fig

Problem

Two systems needed replacing while in use — one moving real money, one a client's live product. A big-bang cutover on either is not a defensible risk.

Applied

The legacy path stays live and test-covered while the replacement is built beside it, and is repointed only once the new path has earned the traffic. The old implementation is retained as a tested reference rather than deleted.

Evidence
  • signal-to-alpha · trading_view_pine/supervisor.py → app/v2/Per-account supervisor kept live across nine sequenced PRs; deployment manifests repointed only in the final phase
  • partsmagic-backend · Part → Item generalizationSchema first, then backend routes, then every frontend call site, then route moves — each step independently shippable

Ports & Adapters

Problem

Two brokerages across five wire protocols — OAuth REST, WebSocket streaming, HMAC-SHA1 request signing, MQTT, and gRPC. Left unmanaged, that variety leaks into the trading engine.

Applied

Order services speak a broker-agnostic vocabulary. Each brokerage's protocol quirks are confined to an adapter, including one whose request signing was reimplemented from the vendor SDK.

Evidence
  • signal-to-alpha · backend/app/adapters/webull_trading.py (App-Key/HMAC-SHA1 signing), webull_mappers.py, webull_stream.py, webull_trade_events.py, public_options.py, discord.py
  • signal-to-alpha · backend/app/v2/ingress/schwab.py, webull.py, webull_translate.py (vendor payload → internal bar model), webull_failover.py

Layered architecture

Problem

A monolithic handler file had grown to hold routing, request validation, business logic and data access together, so no piece could be tested without the others.

Applied

Split into route → middleware → controller → service → data, with the ORM at the boundary. In the dispatch API this was an explicit refactor of an existing monolith, followed by unit and functional suites that the previous shape could not support.

Evidence
  • partsmagic-backend · src/13 route modules, 10 middlewares, 12 controllers, 12 services, Prisma at the boundary
  • firedepartmentapi · api/Refactored from a monolithic handler — commit "separating by function such as router, controller and services"

Backend-for-Frontend proxy

Problem

A browser bundle that calls a third-party API directly must carry the credential, which means shipping it to every visitor.

Applied

The client calls a same-origin route; credentials are injected server-side and never enter the bundle.

Evidence
  • document-intelligence-platform · frontend/app/api/proxy/route.tsServer-side proxy holding the API key
  • partsmagic-frontendClient points at /api; the proxy adds the API key server-side

Anti-Corruption Layer

Problem

A legacy system owned part of a workflow the new API had to participate in. Letting its data model spread through the new controllers would have made it permanent.

Applied

One controller translates between the new availability model and the legacy update loop, containing legacy semantics so the old system can be retired without unpicking it from everything downstream.

Evidence
  • firedepartmentapi · api/controllers/legacyLightboard.controller.jsTranslation boundary between the new model and a legacy service's update loop

Behavioral

Strategy

Problem

Interchangeable algorithms selected at runtime — trading strategies, deployment verticals, and LLM providers — each needing to vary without the calling code branching on type.

Applied

A base class or interface defines the contract; implementations register and are chosen at runtime. The trading registry is shared by both engine generations, so the newer engine did not fork the algorithms.

Evidence
  • signal-to-alpha · backend/trading_view_pine/strategy.py:20Base class defining the evaluation contract; four implementations interchangeable at runtime via a registry
  • partsmagic-backend · src/schemas/variant/ + services/variantProfile.service.tsThe deployment's vertical selects field set and persistence behaviour
  • resume-portfolio · lib/ai-provider.tsProvider chosen at runtime from the database rather than bound at import

Registry / Factory

Problem

Adding an implementation should not require editing the code that selects between them.

Applied

Implementations self-register under a key; factories resolve configuration to a concrete instance at construction time.

Evidence
  • signal-to-alpha · backend/app/v2/shared/bus.py:148make_bus() resolves the transport from environment configuration
  • partsmagic-backend · src/services/variantProfile.service.ts:21profileFieldName() resolves the active vertical to its profile column

Observer

Problem

Many clients need the same live updates, and a naive implementation pushes to only the most recent connection while leaking the rest.

Applied

A connection registry keyed by identity, supporting multiple connections per user, with keep-alive to survive intermediary idle timeouts and pruning of dead sockets.

Evidence
  • signal-to-alpha · backend/app/services/websocket.pyConnectionManager keyed by user_id, multiple connections per user, auto-prunes dead sockets
  • firedepartmentapi · api/controllers/system.controller.js:86SSE client registry with per-connection keep-alive; disconnects handled on close rather than error, per the spec — where a naive implementation leaks

Persisted State Machine

Problem

A multi-stage exit means a position is partway through a plan at any moment. Held in memory, a restart loses the plan; held globally, a later rule change silently rewrites positions already in flight.

Applied

Stage and its associated state are persisted per position, including the policy the position was opened under, so a restart resumes the plan and a mid-flight configuration change cannot alter an open trade retroactively.

Evidence
  • signal-to-alpha · paper_positions schemaPer-position stage and protection state persisted rather than held in process memory
  • signal-to-alpha · commit “persist the exit policy a position opened under”The position remembers the rules it was opened under

Chain of Responsibility

Problem

Cross-cutting request concerns — authentication, authorization, header checks, validation — needed composing, and their order turned out to be load-bearing rather than cosmetic.

Applied

Ten composable middlewares with a documented ordering constraint. One must run before schema validation: the validator strips unknown keys, so a cross-variant write would otherwise return 200 while silently discarding the client's data.

Evidence
  • partsmagic-backend · src/middleware/rejectForeignVariantFields.tsOrdering requirement documented in-source, because a later maintainer would otherwise tidy it into the wrong position
  • partsmagic-backend · src/middleware/checkApiKey, checkClientHeader, checkAuth, checkRefresh, checkSelfOrAdmin, requireAdmin, validate, validateRequest

Specification / Policy Object

Problem

Risk conditions written as inline conditionals inside an engine cannot be tested in isolation, and multiply until no one can enumerate them.

Applied

Each guard is an independently testable predicate over context. Quality checks return typed violation objects rather than a boolean, so a failure says what is wrong rather than only that something is.

Evidence
  • signal-to-alpha · backend/app/v2/shared/reentry_guard.py, same_symbol_guard.py, account_admission.py, account_protection.py, execution_policy.py, trade_window.py, market_hours.py
  • resume-portfolio · lib/resume-quality.ts:154assessResumeQuality returns typed QualityViolation objects rather than a pass/fail

Structural

Facade

Problem

Two engine generations both had to answer “should this position close”. Reimplementing that logic for the newer one would have been cleaner to read and considerably more dangerous.

Applied

The original engine's gate and exit logic is re-exported through facades the new executor calls, so both run the same risk code rather than two copies that can diverge.

Evidence
  • signal-to-alpha · execution_gates.py, exit_manager.pyShared risk implementation across both engine generations

Decorator

Problem

Retry logic repeated at every outbound call site drifts, and a caller cannot distinguish “failed once” from “exhausted every attempt”.

Applied

Async and sync retry decorators with exponential backoff plus jitter and retryable-status awareness, raising a distinct exhaustion exception.

Evidence
  • signal-to-alpha · backend/app/utils/retry.pyretry (:43), retry_sync (:96), backoff with jitter (:148), RetryExhausted (:30), 429/5xx awareness

DTO / Schema at the boundary

Problem

Untrusted input reaching business logic unvalidated, and model output that claims to be JSON without being it.

Applied

Schemas validate at every boundary — request bodies, LLM responses, generated documents — with clamping and derived-field fallback where a partially valid response is still usable.

Evidence
  • partsmagic-backend · src/schemas/11 Zod schema modules; matching form schemas on the client
  • signal-to-alpha · AICritiqueResult.model_validatePydantic validation with clamping and derived-field fallback on malformed model output

Reliability

Idempotency Key

Problem

Message buses redeliver and network calls get retried. Guarding against double execution in application code means trusting every future code path to remember the check.

Applied

Uniqueness is enforced where it cannot be bypassed: a database constraint across signal, subscriber and mode, plus idempotent client order identifiers at the broker boundary. A duplicate fails at the write rather than placing a second order.

Evidence
  • signal-to-alpha · signal_deliveriesUNIQUE(signal_id, user_id, mode) makes bus fan-out idempotent at the database
  • signal-to-alpha · order serviceIdempotent client order IDs prevent duplicate fills on retry

Circuit Breaker / fail-fast

Problem

A dependency that fails silently and indefinitely is worse than one that fails loudly, because nothing escalates.

Applied

Consecutive-failure caps convert a stuck operation into an explicit error state; a failed deployment health check rolls the container back automatically rather than serving a broken build.

Evidence
  • signal-to-alpha · order status pollingMarks an order ERROR after a consecutive-failure cap rather than polling forever
  • partsmagic-backend · deploy pipelineAutomatic container rollback on failed health check

Bulkhead

Problem

One account's failure taking down every other account's trading.

Applied

Independent failure domains per account — originally process isolation, now per-subscriber coroutines whose failure does not propagate to siblings.

Evidence
  • signal-to-alpha · per-subscriber executorsIsolated failure domains; a crash is contained to one subscriber

Rate Limiter (token bucket)

Problem

Concurrent executors independently calling a brokerage will burst past its quota, and the resulting throttle lands on whichever request happens to be a live exit.

Applied

A shared token-bucket limiter with blocking and non-blocking acquisition, wired across live broker call sites so the burst is shaped before it leaves the process.

Evidence
  • signal-to-alpha · backend/app/v2/shared/rate_limiter.py:25RateLimiter with try_acquire (:39) and blocking acquire (:54)

Graceful degradation & failover

Problem

A market-data stream that wedges without disconnecting looks healthy while delivering nothing.

Applied

Stall detection gated to market hours, automatic failover to REST polling, an application-level heartbeat replacing a protocol keepalive the vendor rejects, and a free-tier data path when no brokerage is connected.

Evidence
  • signal-to-alpha · MQTT ingress failoverAuto-failover from a wedged stream to REST polling, with operator paging
  • signal-to-alpha · streamer_service.pyProtocol PING disabled — the vendor closes connections that send them — replaced by an application-level heartbeat timeout

Expand/Contract migrations

Problem

A schema change deployed in one step breaks whichever of the old and new code is running when it lands.

Applied

Additive change first, backfill, then contract — with relation changes executed as schema-then-logic across separate migrations.

Evidence
  • signal-to-alpha · backend/migrations/versions/110 Alembic migrations including expand/contract drops, FK on-delete additions and dedupe migrations
  • partsmagic-backend · prisma/migrations/27 migrations including a one-to-many relation change split into schema and logic steps

Feature Toggle

Problem

Risk-sensitive behaviour should be deployable before it is enabled, and reversible without a rollback.

Applied

Transport selection, provider choice, deployment vertical, and per-account dry-run all read from configuration; compatibility flags ship dormant ahead of the rollout that turns them on.

Evidence
  • signal-to-alpha · SIGNAL_BUS, AI_PROVIDER, per-account dry_runTransport and provider swap by configuration; dry-run isolates live execution per account
  • partsmagic · NEXT_PUBLIC_VARIANTBuild-time vertical, asserted against the server at runtime

Testing

Golden / characterization tests

Problem

Generated output cannot be asserted literally, so a prompt change that quietly degrades quality ships unnoticed.

Applied

Properties are asserted over generated output against fixed input fixtures — evidence coverage, absence of unsupported claims, utilisation floors — so a regression fails CI rather than reaching a reader.

Evidence
  • resume-portfolio · lib/resume-quality.golden.test.tsProperty assertions over rendered output against golden fixtures

Contract / roundtrip testing

Problem

Unit tests with mocked boundaries pass while the actual API contract breaks, which is precisely the failure a live migration produces.

Applied

Scripted roundtrips exercise the real API surface end to end, run at each step of a cutover rather than only at the end.

Evidence
  • partsmagic-backend · 9 roundtrip scripts + verify:openapiitems, taxonomy, search, cutover, location, labels, placeholder, fitment and seed roundtrips against a live API
  • partsmagic-frontend · roundtrip Vitest projectClient suite run against a live backend URL; MSW isolates the rest at the HTTP boundary

Baseline-diff verification

Problem

“The migration introduced no regressions” is an assertion, not a measurement — especially in a suite with known order-dependent failures, where a raw pass count misleads in both directions.

Applied

The change is stashed, the suite run, and the results compared against the same suite with the change applied. The claim is then a difference rather than an impression.

Evidence
  • signal-to-alpha · engine migrationZero-new-failure claim established by stashed-baseline comparison
  • resume-portfolio · lib/published-claims.test.tsGuardrail verified by running it against pre-fix content and confirming it fails

Multi-tenant isolation suites

Problem

Cross-tenant leakage is the worst available bug in a system holding brokerage credentials, and it is invisible to single-tenant tests.

Applied

Dedicated suites assert that per-user scoping holds across the data layer and the execution path, alongside guardrail suites covering the risk limits.

Evidence
  • signal-to-alpha · backend/tests/Tenant-isolation and guardrail directories within a suite of 4,857 collected tests