Interfaces, Data & APIs

Research and production systems fail at boundaries. Typed contracts, explicit schemas and idempotent interfaces keep malformed data and retries from becoming silent corruption.

Section 2 of 5 · 8 units · about 35 hours

0/8

By the end you can Expose one typed service through CLI and HTTP, ingest malformed and old-version records safely, and defend the schema, transaction and idempotency boundaries.

Units

Build it

Mini project · about 12 to 16 hours

One run service behind a CLI and an HTTP API, on PostgreSQL

Turn taskrunner into a service with one service layer behind a CLI and an HTTP API on PostgreSQL. Version the payload, migrate the schema both ways, and prove transaction, isolation and idempotency behavior with tests.

  1. 1Write RunService against a RunStore protocol with an in-memory fake for unit tests, validate the boundary model strictly, and test configuration precedence with the AlgoMaster Interfaces and Protocols exercise as reference.
  2. 2Add a batch import that streams JSON Lines or CSV, quarantines malformed rows with line numbers, and writes accepted rows to Parquet with round-trip type and null checks.
  3. 3Migrate the schema with Alembic through an upgrade, downgrade and re-upgrade round trip on a scratch database, and test the versioned payload in both directions following the Alembic tutorial downgrade round trip.
  4. 4Debit credits and insert the run in one transaction with a rollback test, then reproduce a serialization anomaly under REPEATABLE READ with a bounded retry, following the PostgreSQL transactions tutorial.
  5. 5Predict each read query's row count before running it, then compare the listed filter's plan before and after adding its index and name one query the index does not help, using the AlgoMaster LEFT JOIN and GROUP BY exercises as reference.
  6. 6Serve the same service through a CLI and a FastAPI app over the untouched service layer, testing the status-code contract, the capped page and store swapping with the FastAPI tutorial Testing extended example.
  7. 7Make submission idempotent with an Idempotency-Key ledger claimed in the same transaction as the debit, and prove a replay stores one run while a mismatched body is rejected.
What you hand in
  • The service package: RunService, the fake and PostgreSQL stores, the CLI and the FastAPI app.
  • Alembic revisions with the round-trip transcript and both-directions payload tests.
  • Transaction, isolation, idempotency and import tests with quarantine file, plans and predictions.
How to check it
  • Self-grade with the rubric below
How it's graded

One service layer

Pass: The CLI and HTTP paths call the same service, the service module stays transport-free, and both stores pass the suite.

Great: One parametrized suite runs every service test against the fake and the PostgreSQL store.

Boundaries and evolution

Pass: Malformed, extra-field and cross-version payloads are rejected with field-level errors, and the migration round trip succeeds.

Great: The write-up classifies each schema change as additive or breaking and names which old clients keep working.

Transaction behavior

Pass: The failed debit leaves credits and run count unchanged, and the anomaly test retries to the correct balance.

Great: The retry loop is also tested with an injected serialization failure and stops clearly at its limit.

HTTP contract and idempotency

Pass: Created, validation-error, not-found and capped-page behavior hold, and a keyed double submission stores one run.

Great: A same-key different-body request is rejected, and a replay returns the stored response unchanged.

Data evidence

Pass: The import quarantines malformed rows with line numbers without loading the whole file, and each query matches its predicted count.

Great: The plan comparison states table size and buffers, and explains the query the index does not help.

Resources

  • Official docs typed-service build pathPython typing, Pydantic, FastAPI and PostgreSQL

    Build one record service in this order: structural protocols and generics; Pydantic models, validators, strict mode, serialization and settings; FastAPI request bodies, dependencies, errors and tests; then PostgreSQL transactions and EXPLAIN. Replay valid, malformed, duplicate and previous-schema requests through CLI and HTTP.

  • AlgoMaster SQL - selected routeAlgoMaster

    Study SQL Foundations, Querying Data, Joins, Subqueries and CTEs, Window Functions, DDL, DML and Views, Performance Optimization, Transactions and Concurrency, and Data Modeling. Stop when the service queries and transaction tests pass.

  • PostgreSQL transactions and EXPLAINPostgreSQL

    Use the transaction tutorial and EXPLAIN guide to demonstrate commit, rollback, one isolation anomaly or prevented anomaly, and a measured plan improvement on the database actually used.

  • FastAPI tutorialFastAPI

    Use Request Body, Dependencies, Handling Errors and Testing to expose the same service layer through HTTP. Keep framework models outside the domain core and preserve the same error semantics as the CLI.

  • AlgoMaster Low-Level Design - one rehearsalAlgoMaster

    Use one fitting design prompt to rehearse interface contracts, dependency direction and failure ownership. Treat the review as feedback, then verify behavior with your own tests.

  • Stas' Python Cookbook - data and interfacesStas Bekman

    Use Serialization and Deserialization plus Environment and Arguments for focused implementation help. Compare JSON, JSONL, CSV and compressed data, and never use pickle for untrusted interchange.

  • AlgoMaster Python - interfaces, generics and data filesAlgoMaster

    Use Interfaces and Protocols plus Generic Types for structural typing, and Working with JSON plus Working with CSV for JSONL, error handling, newline and DictReader behavior. Lesson quizzes check recall; implementation is verified with your own scripts.

  • Alembic tutorial - migration scripts and downgradingSQLAlchemy

    Use Create a Migration Script, Running our First and Second Migration, Getting Information and Downgrading to run a paired upgrade and downgrade round trip on a scratch database.

  • PyArrow Parquet read and write docsApache Arrow

    Use Reading and Writing Single Files plus Table from_pydict and from_pylist to convert normalized records to Parquet and test types, nulls, column projection and schema.

  • Stripe idempotent requestsStripe

    Use the Idempotency-Key header contract, stored-response replay, parameter-mismatch errors and POST-only scope to implement keyed replay for one endpoint.

  • SQLAlchemy 2.1 documentation - select, Session and eager loadingSQLAlchemy

    Use the select() tutorial for 2.x query style, Session basics for the transaction boundary and identity map, and relationship loading for lazy versus selectinload versus joinedload plus raiseload. Use select() style and Session.execute or Session.scalars only, never the legacy Query API.