Skip to content
Browse the docs

HTTP API (v1)

View on GitHubReport a problem with this page

Base path: /api/v1. JSON uses camelCase. A request body's keys the API does not know are ignored; a design document in a body is still validated against the schema, which refuses unknown keys. Without sign-in (ARCHSIM_AUTH_MODE=none, the default) the API is local and single-user: every request is the local owner of the default workspace. With ARCHSIM_AUTH_MODE=oauth people sign in, and projects and runs belong to workspaces they are members of (see Sign-in, workspaces and tokens and SECURITY.md).

  • OpenAPI document: GET /api/v1/openapi.json
  • Interactive docs: GET /api/v1/docs
  • Hosted, the API is reached through the web server: https://<host>/api/v1/....

Errors#

Domain errors use one shape:

{
  "detail": {
    "message": "Cannot simulate: Redis Cache can miss (hit ratio 80%) but nothing reads the data on a miss: ...",
    "issues": [
      {
        "severity": "error",
        "code": "cache.miss_unrouted",
        "message": "Redis Cache can miss (hit ratio 80%) but nothing reads the data on a miss: its 'miss' port is not connected and API Servers has no link set to 'Reads only on a cache miss'.",
        "nodeId": "cache",
        "edgeId": null,
        "path": null,
        "hint": "Cache-aside: give the service a link to the database with 'Reads only on a cache miss' on. Read-through: connect the cache's 'miss' port to the database."
      }
    ]
  }
}
Status When
400 Contradictory request (e.g. both document and exampleId).
400 Also: a request Spring Security's request firewall refuses (a method other than GET, HEAD, POST, PUT, PATCH, DELETE and OPTIONS, a path that is not normalized or holds an encoded %, . or backslash), answered {"detail": "Bad Request"}.
401 Sign-in is on, and the request has no valid session cookie or API token where the endpoint needs someone, or carries a wrong API token wherever it goes, public endpoints and unknown paths included (WWW-Authenticate: Bearer). A token sent to the sign-in paths of a provider set up here is not read.
403 Your role in the workspace is too weak (a viewer editing), a change a session cookie signs in without the right X-ArchSim-CSRF header (wherever it is sent), or an API token doing what only a signed-in person may.
404 Unknown project, run, example or workspace, or one in a workspace you are not a member of (the same answer, so ids reveal nothing).
409 Revision conflict on save; report requested for an unfinished run; comparing unfinished runs; a workspace's last owner leaving; a project past a workspace's project limit.
413 Request body larger than ARCHSIM_MAX_BODY_BYTES.
422 Document invalid (with issues), run too large, a calibration that cannot be done, or a request body or query that does not fit (a detail list of type, loc, msg and input, as FastAPI's was).
429 A rate limit (runs per hour, sign-in attempts, ...): wait the Retry-After seconds.

Meta#

Method Path Description
GET /health 200 {"status": "ok", "database": "ok"}; 503 {"status": "degraded", "database": "unavailable"} when the database cannot be reached, so health checks take the instance out of service.
GET /meta ArchSim's version (version), engine/schema/report versions, database dialect, run limits.
GET /pricing Price sources a design can name in pricing: generic (illustrative rates) and every price snapshot on this machine (provider, region, date, file, sha256 of its content, newest for the newest of its provider and region). A design pins one with pricing.snapshotDate. See pricing.md.
GET /components Component catalog: ports, field descriptors (kind, unit, range, group, assumption flag, visibility), defaults, modeled/not-modeled notes, presets (with tier and sources, the links behind documented preset numbers), technologyTraits, technologyDefaults, technologySources (links behind documented defaults) and technologyTiers (core or experimental); plus edgeFields, workloadFields and tierNote (the text of the "experimental" badge).
GET /schema/architecture JSON Schema of the document.
GET /examples Bundled example documents (id, name, description, tags, scenario count).
GET /examples/{exampleId} One example document.
POST /validate Body {document, scenarioId?}. Returns {valid, issues[]}; never saves or simulates.
POST /export Body `{document, format: "compose"
POST /import Body `{format: "compose"
POST /calibrate Body `{document, source: "prometheus"
POST /analyze Body {document, scenarioId?}. Returns what a run would use, computed by the engine without simulating: sizing (per part: specs simulated with their source set/auto/scenario, auto sizes, peakRps, why, pricePerHour, sku with a price snapshot), cost (monthly estimate by part; each line's priceSource is set (by the user), snapshot (with sku and snapshotDate), preset (a technology preset's illustrative price), size or default; pricing names the source, with the snapshot's sha256), review (design review findings), reviewCounts, reviewRules, peakRps, technologies (each part's technology and tier), inputs (every performance input with its value and provenance: measured, documented, assumed or illustrative), provenanceCounts, calibration, estimate (what queueing formulas predict at the peak, without simulating: utilization and wait per part, the busiest part, a mean and a rough p95 latency, or where it saturates) and confidence (level high/medium/low, reason, reasons, drivers, howToRaise; parts weighted by their estimated utilization). See simulation-model.md. 422 with issues when the document cannot be read. The web app calls it with live validation; archsim analyze prints the same. quickCheck says whether a quick check (mode: "sampled") can answer the design: {eligible, reason, requestedS, simulatedS, sampleS}.

Projects#

Method Path Description
GET /projects The workspace's projects (most recently updated first) with node and scenario counts.
POST /projects Create in the workspace (editors) from {document}, {exampleId}, or blank. Optional name, description. 201. With {exampleId, reuseUnedited: true} and no name, returns the most recent copy of that example you made in this workspace that was never saved and still matches it (200) instead of creating another; the web app opens templates this way. Someone else's copy is never handed back.
POST /projects/import Body: a raw document (older schema versions are migrated). Optional ?name=. 201.
GET /projects/{id} Project with its document and revision.
PUT /projects/{id} Body {name?, description?, document?, expectedRevision?}. Increments revision; 409 if expectedRevision is stale.
DELETE /projects/{id} Deletes the project and its runs. 204.
POST /projects/{id}/duplicate Copy as "Name (copy)". 201.
GET /projects/{id}/export The document as a download (Content-Disposition: attachment).

Lists and new projects use the request's workspace: ?workspace=<id> or the X-ArchSim-Workspace header, else your personal workspace, else default. A project or run asked for by id uses its own workspace: viewers read, editors change, create, simulate and delete, and anyone without a role there gets 404.

Saving accepts documents that are schema-valid even if graph validation fails (for example a dangling cache miss port), so work in progress can be stored. Simulation requires a fully valid document. Schema-invalid documents (unknown keys, out-of-range link settings, wrong schemaVersion) are rejected with 422. The project name is authoritative and is copied into document.metadata.name.

Runs#

Method Path Description
POST /projects/{id}/runs Body {scenarioId?, label?, document?, seeds?, mode?}. Validates, then enqueues. 202 with the run. document simulates unsaved edits; it is stored with the run. seeds (1-10, default 1) above 1 starts a seed group: one run per seed from the document's seed (base) to base + seeds - 1, all of one stored document, each with groupId and seedIndex; the answer is the first run. A workspace runs at most 5 seeds at once when hosted (10 without sign-in), and the group counts as that many runs against the hourly limits. mode: "sampled" is a quick check: the run is answered from a steady sample when it can be (see /analyze quickCheck; 422 with the reason when the design does not qualify), and its report carries simulationMode. Seed and mode are stored with each run.
POST /projects/{id}/runs/batch Body {scenarioIds: [..], document?} (1-10 entries; null = base document). Validates all before enqueueing any. 202 with a list.
GET /projects/{id}/runs Recent runs (newest first, up to ARCHSIM_RUN_HISTORY_LIMIT, default 200), without reports.
GET /runs/{runId} Status, progress (0-1), error, seed, digests, and a small summary once finished. Poll this.
GET /runs/{runId}/report Full report (409 unless succeeded). See below.
GET /runs/{runId}/input The exact document submitted for the run (re-importable).
POST /runs/{runId}/cancel Cancels a queued run immediately. A running one is stopped by the worker holding it, on any instance, within about 2 s (its next heartbeat; at once when that worker is in the same process); one still going ARCHSIM_CANCEL_GRACE_SECONDS (10 s) later is killed. The response shows cancelled, or running while the cancel is on its way.
POST /runs/{runId}/rerun Re-simulates the stored input with the same scenario, seed (a seed group's run keeps its own) and mode. Response has reproducesRunId; compare resultDigest values, which match on the same engine (a Python run re-run in Java agrees to the parity bar and need not share its digest). 202.
GET /run-groups/{groupId} A seed group: kind, baseSeed, size, mode, scenarioId, label, status (running, then succeeded, partial or failed), its runs by seed, and summary from the engine's summarize_seeds against the objectives of the document the runs used: met/missed/undecided of finished, verdict (holds, fails, borderline when the runs disagree, or null), confidenceCap (medium when borderline), latencyMs.p50/p95/p99, successRate and throughputRps ranges ({min, max, median}), and text ("Meets the objectives in 4 of 5 runs · p95 98–131 ms (median 104) · seeds 42–46"). Viewers of the workspace; others get 404.
DELETE /runs/{runId} Cancels if active, then deletes. 204.

Run status: queued, running, succeeded, failed, cancelled. A failed run has error.message and, for document problems, error.issues. progress is read from the database, where the worker simulating the run writes it at most once a second, so every API instance reports the same value.

Background runs and several instances#

Runs are queued in the database, and workers (archsim-app worker, ADR-0053) take them: the API only queues. Each run simulates on a thread of its own, up to ARCHSIM_MAX_CONCURRENT_RUNS at once per worker (default: CPU count - 1), and the runs share the worker's heap, sized for them (archsim-app's README).

  • Restarts. A worker that stops normally (Ctrl+C, SIGTERM) gives its runs back to the queue, and the next worker simulates them again from the start. One that dies without warning (killed, out of memory, host lost) stops renewing its runs' leases; after ARCHSIM_LEASE_SECONDS (30 s) another worker, or the same one after a restart, requeues them. A run whose worker stops twice is failed with "The simulation worker stopped unexpectedly…".
  • A run that exhausts the heap stops its worker, which runs with -XX:+ExitOnOutOfMemoryError (the image, make worker and archsim-app's README start it so), and the worker's other runs stop with it: each is requeued, as above, and failed only if its worker stops a second time.
  • Deadline. A run still going ARCHSIM_MAX_WALL_SECONDS + 30 s after it started is failed, even if the simulation stopped checking its limits; its thread runs on until it stops.
  • Several instances. Any number of API instances and workers can share one database: the API only queues runs, workers claim them one claim at a time under a PostgreSQL advisory lock, and cancel requests reach the worker holding a run wherever it is. Run more workers with java -Xmx… -XX:+ExitOnOutOfMemoryError -jar archsim-app.jar worker (ARCHSIM_MAX_CONCURRENT_RUNS each, with the heap archsim-app's README asks for), or docker compose up --scale worker=3. Hosts need synchronised clocks (NTP): leases compare their times.
  • Migrations (Flyway) take a PostgreSQL lock, so instances starting together migrate one at a time. The migrate role (java -jar archsim-app.jar migrate, the Compose migrate service) migrates once and exits; then set ARCHSIM_AUTO_MIGRATE=false on the API instances. Workers never migrate.
  • Workers table. job_workers lists each worker's latest heartbeat (every 2 s), slots and runs in flight; rows of workers gone for an hour are deleted.

Report shape#

{
  "reportVersion": "1.13",
  "window":     { "warmupS", "durationS", "measuredS", "drainS", "simulatedS" },
  "summary":    { "offeredRps", "throughputRps", "successRate", "latencyMs": {p50, p95, ...},
                  "latencyWithFailuresMs", "latencyByOp", "failureBreakdown": [...],
                  "accounting": {...}, ... },
  "timeseries": { "bucketS", "t": [...], "offeredRps", "throughputRps", "errorRps",
                  "timeoutRps", "attemptRps", "latencyP50Ms", "latencyP95Ms", "latencyP99Ms" },
  "nodes":      [ { "id", "type", "label", "status", "statusReasons", "summary", "accounting",
                    "timeseries": { "utilization", "queueMean", ... }, "config" } ],
  "edges":      [ { "id", "source", "target", "callRps", "retries", "timeouts", ... } ],
  "findings":   [ { "severity", "kind", "nodeId", "title", "detail", "suggestion"?, "evidence" } ],
  "assumptions":{ "modelNotes", "technologies", "userInputs", "provenanceCounts", "calibration",
                  "components", "validationWarnings" },
  "sizing":     { "auto", "targetCpuUtilization", "nodes": { id: { "specs", "auto", "why", ... } } },
  "cost":       { "monthly", "perMillionRequests", "byNode": [...], "notes", "hasCost", ... },
  "review":     [ { "severity", "rule", "title", "detail", "suggestion", "nodeIds", "edgeIds" } ],
  "estimate":   { "method", "atRps", "latencyMs": {mean, p95}, "busiest", "overloaded",
                  "saturationRps", "summary", "paths", "breakdown", "parts": [...], "notes" },
  "confidence": { "level", "reason", "reasons", "drivers": [...], "weightedBy", "howToRaise" },
  "input":      { resolved document that was simulated (auto sizes filled in) },
  "provenance": { "engineVersion", "schemaVersion", "seed", "scenarioId", "scenarioName",
                  "overrides", "inputDigest", "resultDigest", "requestsGenerated",
                  "eventsProcessed", "wallSeconds", "python", "simpy" }
}

Metric definitions are in simulation-model.md; confidence and estimate (report 1.13+) in its Confidence and Instant estimate sections. Neither is part of resultDigest, which covers summary, timeseries, nodes, edges and window.

Sign-in, workspaces and tokens#

GET /auth/config says which mode the server runs in (none or oauth) and its sign-in providers. In none mode there is nothing to sign in to and nothing below needs a header.

Signing in (browser). GET /auth/{github|google}/login?next=/path redirects to the provider (OAuth 2 with PKCE); the provider returns to GET /auth/{provider}/callback, which sets the session cookie __Host-archsim_session (HttpOnly, Secure, SameSite=Lax) and the CSRF cookie __Host-archsim_csrf, then redirects to next (a path on this site), or to /signin?error=state|denied|provider|disabled. POST /auth/logout ends the session (?everywhere=true: all of yours). Every request that changes something with the session cookie must send X-ArchSim-CSRF: <csrfToken> (from GET /auth/me or the CSRF cookie) along with the CSRF cookie itself, or it gets 403, before the API looks at the path; the header is the only place the token is taken from, never a form or query parameter. The token is a random value in the cookie, which signing in sets for as long as the session lasts; when it is gone, GET /auth/me sets a new one, for the browser's session.

Trying ArchSim without signing in (browser). With ARCHSIM_SANDBOXES=true (hosted only; ADR-0079), GET /auth/config answers sandboxes: true and the browser's csrfToken, which it also sets in the CSRF cookie. POST /auth/sandbox, sent with that token as X-ArchSim-CSRF and the cookie, makes a guest account (named "Guest", no email) that owns a new sandbox workspace, and signs the browser in as the guest: 201 with what GET /auth/me answers, and the session and CSRF cookies, which last until the sandbox is deleted, 24 hours later, with the guest and everything in it. A guest uses the sandbox as its owner, within its limits, but makes no team workspaces, API tokens, invitations or share links and accepts no invitation (403). Signing in from a sandbox starts a normal personal workspace; the sandbox's projects are not moved.

API tokens (CLI, CI, MCP). Send Authorization: Bearer asim_pat_...; no cookie and no CSRF header. A token acts as you, as a viewer if its scope is read, and only in its workspace if it names one. A revoked, expired, mistyped or malformed token is refused with 401 wherever it is sent, public endpoints included, so a client learns at once that its token is wrong; a request with no token reaches public endpoints as before. The exception is the sign-in paths (/auth/{provider}/login and /callback of a provider set up here), browser navigations that Spring Security's OAuth2 login answers first: a token sent there is not read. With sign-in, GET /.well-known/oauth-protected-resource/api/v1 (RFC 9728's address for the API; the same document is at /.well-known/oauth-protected-resource) describes the API as a protected resource: {"resource": "<public URL>/api/v1", "bearer_methods_supported": ["header"], "tls_client_certificate_bound_access_tokens": false}. The web server passes /.well-known/oauth-protected-resource/**, and nothing else under /.well-known, on to the API, so the document is served at the public address it names.

Method Path Description
GET /auth/config {mode, providers, sandboxes, csrfToken} (csrfToken: where sandboxes are offered, the token that starts one; else null). Public.
GET /auth/me {mode, kind (local, session or token), user {id, name, email, avatarUrl, guest, expiresAt}, workspaces [...], csrfToken}. guest is a sandbox's guest, whose account and sandbox are deleted at expiresAt (null for everyone else). 401 when signed out.
POST /auth/sandbox Starts a sandbox for a visitor who is not signed in (with X-ArchSim-CSRF): 201 with the guest as /auth/me describes them, and the session cookies. 404 where sandboxes are not offered, 409 for a browser signed in already, 429 after 5 starts per address in an hour, 503 (with Retry-After) while the server keeps 500 guests.
GET /auth/{provider}/login Starts signing in (302 to the provider). ?next= is where to land after. 429 after 30 starts per address in 10 minutes.
GET /auth/{provider}/callback The provider's return (302).
POST /auth/logout 204; ?everywhere=true ends every session of the account.
GET /workspaces Yours, with your role, kind (personal, team, sandbox) and limits (maxConcurrentRuns, maxRunsPerHour; null: the kind's).
POST /workspaces {name}: a team workspace you own. 201.
GET, PATCH, DELETE /workspaces/{id} Read (members), rename (owners), delete a team workspace with all its projects and runs (owners; default and personal ones stay).
GET /workspaces/{id}/members Members with their roles.
PATCH, DELETE /workspaces/{id}/members/{userId} {role} (owners); remove someone (owners) or leave (yourself). A workspace keeps at least one owner (409).
GET, POST /workspaces/{id}/invitations Pending invitations; create one (owners of team workspaces) with {role, email?, expiresInDays?} (default 7, at most 30). The answer has the token once: share <web address>/invite/<token>.
DELETE /workspaces/{id}/invitations/{invitationId} Revoke.
POST /invitations/preview {token}: the workspace, role and who invited you.
POST /invitations/accept {token}: join (single use; an invitation with an email needs that verified email).
GET /tokens Your working tokens (prefix, never the secret).
POST /tokens `{name, scope: read
DELETE /tokens/{id} Revoke at once.

Tokens cannot manage tokens, workspaces or invitations (403): do that signed in. Neither can a sandbox's guest, who also makes no share links.

export ARCHSIM_TOKEN=asim_pat_...        # Settings → API tokens
curl -s https://archsim.example.com/api/v1/projects -H "Authorization: Bearer $ARCHSIM_TOKEN"

Limits#

With sign-in (or ARCHSIM_RATE_LIMITS=true) each workspace kind has limits, which a workspace's own maxConcurrentRuns/maxRunsPerHour replace:

Kind Runs at once Runs per hour Largest run Calibration replay Projects Seeds per group
personal 2 60 the server's 20 s no limit 5
team 4 300 the server's 20 s no limit 5
sandbox 1 20 200,000 requests, 20 s 20 s 5 5

Without sign-in a seed group may run 10 seeds (5 in a sandbox). A visitor's sandbox (POST /auth/sandbox) has the sandbox's limits, and is deleted 24 hours after it starts.

Runs at once are counted across every worker (a run waits in the queue until its workspace has room; workers take each workspace's oldest run before anyone's second). A person may also start 300 runs an hour. Starting runs past a limit answers 429 with Retry-After, and a batch is refused whole. The counters live in the database (rate_limits), so every API instance shares them. Without sign-in the counters are off, and only sandboxes keep their other limits.

A share link is a frozen, read-only copy of one finished run's results that anyone with the link can open on the web app at /r/<slug>, without signing in. It holds the report without request traces (calibration addresses hidden), the objectives from the run's input document, the project name and that document (for "Open a copy"; the public answer leaves it out). It does not change when the design does and stays when the run or project is deleted, until it expires or is revoked. Slugs are 128 random bits in base62 (22 characters).

Method Path Description
POST /runs/{runId}/shares Editors: {title?, expiresInDays? (default 30, at most 365; null: never)}. 201 with `{id, slug, path: "/r/", url (when ARCHSIM_PUBLIC_URL is set), title, projectId, runId, createdAt, expiresAt, revokedAt, viewCount, resultDigest, reportVersion, status: active
GET /projects/{id}/shares Viewers: the project's links, newest first (revoked and expired ones included).
GET /shares Viewers: every link of the workspace (?workspace=), including those whose project was deleted.
DELETE /shares/{id} Editors: revoke at once (204); the stored copy is deleted.
GET /public/shares/{slug} No sign-in. {slug, title, projectName, runLabel, scenarioName, createdAt, expiresAt, payloadVersion, reportVersion, resultDigest, objectives, report, canCopy}; ?view=false does not count a view (link previews). 404 alike for unknown, expired and revoked links; Cache-Control: no-store, X-Robots-Tag: noindex. With limits on, 60 answers a minute per address (429 with Retry-After).
POST /projects/from-share {slug, name?}: "Open a copy", a new project in the request's workspace (editors) from the shared design. 201 with the project.

Review: comments, sign-offs and history#

Anyone in a project's workspace reads, comments, resolves threads and signs off, viewers included; editors also change the design. Authors edit and delete their own comments, and owners may delete any. A read token only reads (403 on these changes). People outside the workspace get 404, as for its projects.

Method Path Description
GET /projects/{id}/comments Oldest first; replies carry parentId. Filters: anchorKind, anchorId, runId. Each has author, resolvedAt/resolvedBy (on a thread's first comment), detached (its part or run is gone from the saved design), canEdit, canDelete.
POST /projects/{id}/comments `{anchorKind: node
PATCH, DELETE /comments/{id} {body} (author); delete (author or owner; a thread's first comment takes its replies).
POST /comments/{id}/resolve `{resolved: true
POST /runs/{id}/signoffs `{decision: approved
GET /runs/{id}/signoffs, /projects/{id}/signoffs Newest first. stale once the design was saved again since (currentRevision > projectRevision).
DELETE /signoffs/{id} Withdraw your own sign-off.
GET /projects/{id}/activity, /workspaces/{id}/activity The history, newest first: {items, nextBefore}; pass ?before=<nextBefore> for older ones (limit 1–200, default 50). Each event has action (project.update, run.create, comment.resolve, signoff.create, member.role ...), targetKind/targetId, projectId, actor and actorKind (user, token, system), meta, and ip for owners only.

Every change to a project, its runs, comments and sign-offs, and to a workspace's members and invitations, writes its history row in the same transaction as the change. A project's history outlives the project, in its workspace's history.

Compare#

Method Path Description
GET /compare?a={runId}&b={runId} Both runs must have succeeded. Returns labels, provenance, inputDiff (path, label, a, b), kpis (value, delta, relative delta, verdict better/worse/same), per-node rows, bottleneck for each run, explanations, warnings (different seeds or engine versions) and both time series.

Walkthrough with curl#

API=http://127.0.0.1:8000/api/v1
wait_run() {  # poll until the run leaves queued/running
  while :; do
    s=$(curl -s "$API/runs/$1" | jq -r .status)
    [ "$s" = queued ] || [ "$s" = running ] || break
    sleep 1
  done
  echo "$1: $s"
}

# 1. Create a project from the starter example
PID=$(curl -s -X POST $API/projects -H 'content-type: application/json'   -d '{"exampleId": "cache-aside-starter"}' | jq -r .id)

# 2. Run two scenarios (returns immediately with status "queued")
A=$(curl -s -X POST $API/projects/$PID/runs -H 'content-type: application/json'   -d '{"scenarioId": "one-api-replica"}' | jq -r .id)
B=$(curl -s -X POST $API/projects/$PID/runs -H 'content-type: application/json'   -d '{"scenarioId": "three-api-replicas"}' | jq -r .id)

# 3. Poll until finished
wait_run $A; wait_run $B
curl -s $API/runs/$A | jq '{status, summary}'

# 4. Fetch the full report and its findings
curl -s $API/runs/$A/report | jq '.findings[] | {severity, title}'

# 5. Compare the two runs
curl -s "$API/compare?a=$A&b=$B" | jq '{inputDiff, explanations}'

# 6. Reproduce run A from its stored input and seed
R=$(curl -s -X POST $API/runs/$A/rerun | jq -r .id)
wait_run $R
curl -s $API/runs/$R | jq -r .resultDigest
curl -s $API/runs/$A | jq -r .resultDigest      # same value, on the same engine

# 7. Export and re-import
curl -s $API/projects/$PID/export -o starter.archsim.json
curl -s -X POST $API/projects/import -H 'content-type: application/json'   --data-binary @starter.archsim.json | jq '{id, name}'

Stability#

Paths are versioned (/api/v1). Breaking changes will go to /api/v2. Reports carry reportVersion and documents carry schemaVersion.