Skip to content

Architecture Overview

mavrovde edited this page Nov 13, 2026 · 5 revisions

Architecture Overview

This page describes the language-neutral architecture. It applies to all three candidate stacks; the stack-specific details are on Architecture: Go, Architecture: Rust and Architecture: TypeScript, compared on Stack Comparison.

In one paragraph

viafrei-api is a single, stateless-at-heart service: one binary (in TypeScript, one bundled module on the Node runtime) in a small container behind the existing TLS edge. It authenticates keys, applies the licence gate, rate limits and priority admission in-process, reads the platform's read contract through a read-only database role with a hard 2 second deadline, and answers in the domain's own vocabulary. Keys, plans, audit records and usage counters live in a small, separate access store that the API owns. There is no gateway, no Redis and no external key service at the start; each can be added later if the scale calls for it (see Technology Evaluation).

Components

flowchart LR
  C[Client] -->|HTTPS| E[TLS edge<br/>coarse per-IP guard]
  E --> API
  subgraph API[viafrei-api process]
    MW[Middleware<br/>request id, deadline, auth,<br/>licence gate, limits, quota,<br/>ETag, cache, admission]
    UC[Use cases<br/>one per feature]
    DOM[Domain<br/>pure model and rules]
    SA[Storage adapter<br/>the only code that knows<br/>the read contract]
    AA[Access-store adapter]
    MW --> UC --> DOM
    UC --> SA
    MW --> AA
  end
  SA -->|read-only role| RC[(Read contract<br/>published views)]
  AA -->|own role| AS[(Access store<br/>keys, plans, audit, usage)]
  API -.loopback.-> M[Metrics endpoint]
Loading

Layers and dependency direction

The code is organised as a hexagon (ports and adapters):

Layer Contains May depend on
Domain aggregates, value objects, rules (lamps, severities, price order, the licence decision), read ports the standard library and a geometry type only
Application one use case per feature, composing ports domain
Adapters storage adapter, access-store adapter, HTTP adapter (DTOs, problems, GeoJSON, middleware), cache application, domain, runtime
Runtime configuration, admission controller, rate limiter, metering, telemetry, lifecycle —
Entry point serve, migrate, keys, usage, config, openapi, version subcommands everything

The reverse direction is forbidden and enforced by the build (a lint rule in Go, crate boundaries in Rust, a dependency-cruiser rule in TypeScript). The domain never imports a database driver or an HTTP framework.

The read contract

The platform publishes a versioned set of read-only views (and a few parameterised SQL functions where a view cannot express a bounded query). This is the read contract, and it is the only part of the platform the API can see.

Store Owned by Accessed by the API as Content
Platform internals the platform not reachable everything the platform needs internally
Read contract the platform a read-only role, read-only transactions, a role-level statement timeout and connection limit views shaped for reading, each row carrying its source family and an "as of" time
Access store the API its own small role with write access to this store only keys, plans, terms acceptance, audit log, hourly usage

Why the platform owns the read contract: the view definitions refer to internal storage, which must stay private. The API repository receives only a contract file: the list of views, columns, types, nullability, code lists and the contract version. No view body and no internal name is in it. What the contract describes, in substance, is the logical read model on Data Model: entities, fields, keys, code lists and retention classes under neutral names.

Why the API owns the access store: keys and plans are the API's own domain. (Whether it is a separate schema or a separate small database is an open owner decision; see Project Status.)

Keeping the API independent of platform storage

  1. Compiled dependency direction: only the storage adapter sees contract types.
  2. One shared artefact: the contract file, generated by the platform from a migrated test database and delivered to the API repository by a version-sync pull request.
  3. Contract tests on both sides: the platform's CI fails if the views drift from the contract file without a version bump (and a removal or retype without a major bump). The API's CI builds a stub database from the contract and compiles every query against it.
  4. Mapping tests: every column read exists; every contract code maps (with other as an explicit entry); planted rows (nulls, extreme prices, geometry across a state border, instants at a daylight-saving change) map as expected.
  5. The public shape has its own gate: breaking-change detection on the OpenAPI document and JSON snapshots per feature.
Change on the platform side Read contract API
New data source in an existing family unchanged nothing
Internal storage renamed or split view body changes, contract unchanged nothing
New code value minor contract bump one mapping line (until then: other plus a metric)
A new feature needs data a new view, minor contract bump adapter, use case, DTO
Column removed or retyped a new contract version beside the old one move the adapter, then the platform retires the old version

A storage rename changes at most one mapping line; it never changes a public payload.

Request lifecycle

sequenceDiagram
  autonumber
  participant E as Edge (TLS)
  participant M as Middleware
  participant U as Use case
  participant S as Storage adapter
  participant P as PostgreSQL
  E->>M: GET /v1/motorways/A8/conditions
  M->>M: request id, deadline = now + 2 s
  M->>M: key: checksum, cache lookup, constant-time compare
  M->>M: licence gate → allowed source families
  M->>M: rate limit, then quota
  M->>M: ETag matches freshness? → 304, no database work
  M->>M: result cache hit? → 200
  M->>M: admission: permit for this tier, or 429 + Retry-After
  M->>U: validated query in domain types
  U->>S: port call with request scope
  S->>P: read-only transaction, statement_timeout = remaining budget, query limited to allowed families
  Note over S,P: deadline reached ⇒ cancel request sent to PostgreSQL, the connection is reused only if clean
  P-->>S: rows
  S-->>U: domain objects + provenance (each row checked against the gate again)
  U-->>M: result
  M-->>E: JSON + meta, ETag, Cache-Control, RateLimit headers, permit released, usage counted
Loading

The cheap checks come first. A 304 is answered before admission, so it never takes a database permit.

Deployment shape (design)

  • One container, run as a non-root user, read-only filesystem, no secrets baked into the image.
  • Listens on a loopback port behind the existing TLS edge; the metrics endpoint is loopback only.
  • Assumption: the first deployment runs one instance with a tight memory limit and a small, hard-capped share of database connections. A later stage grows the pool sizes by configuration only, and a read replica, a central connection pooler and shared rate-limit state become options. See Roadmap.

Scaling stages (qualitative)

Stage Shape What changes
Start one instance with tight limits in-process limits and cache are exact; strict database share
Growth one instance with more capacity larger pools and cache by configuration
Scale-out several instances shared limit state (Valkey), a central pooler (PgBouncer), possibly a read replica and a thin gateway

Nothing in the design assumes the later stages; each is an addition, not a rewrite.

Home

About

Design

Data Model

Technical specification

Testing

Engineering

Technology choice

Reference

Clone this wiki locally