8.3 Persistence¶
This file: the kinds of store FeeCheck uses and why, their consistency — ACID inside the relational database, one instance without a replica, eventual consistency between the stores — how the case is kept in the relational store — repositories, aggregates, one aggregate per transaction, locking, change history, test data — how the schema changes, retention, backup and the connection budget, as concepts. No tables or columns: the case's types are in 8.11, its tables in 8.19.
One relational database holds the case, the case engine's tables and the outbox of the event
backbone, so that a case's change, the engine's step and the event that reports it commit in one
transaction (8.16.3; ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md)).
It is the authoritative store for everything that belongs to a case, its business values included.
Beside it an object store keeps the uploaded PDF, and a document database keeps derived copies only,
each rebuildable at any time (ADR-0018 (docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)).
| Store | Holds | Technology | Why this kind of store | Status |
|---|---|---|---|---|
| Relational database | the case and its pages, and the event publication registry (the outbox) | PostgreSQL 18; Cloud SQL on Google Cloud, one shared-core instance reached over its private IP (ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md)); Spring Data JDBC, the schema owned by Flyway (ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md)) |
transitions that must be atomic, filters and counts across cases, a schema under version control — below | the case and its pages built (spec 457 (docs/specs/457-case-store-postgres.md)); the registry's table, its staleness monitor and resubmission built, no event published through it yet |
| Relational database, case engine | the case engine's own tables | the same PostgreSQL | the engine's step commits with the case's change | planned |
| Relational database, business data | attribute values, master-data comparisons, findings, the audit trail; the cache of register answers, valid per source as the policy says; a register's bulk ingest for the offline profile, with its source version | the same PostgreSQL | joined with the case and with each other, reported on in SQL | planned |
| Vector store | the embeddings of the compiled business document and of the converted text (ADR-0018 (docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)), and of the assistance's knowledge base |
pgvector in the same PostgreSQL, through Spring AI's vector store abstraction (ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md)) |
the embeddings sit beside the rows they belong to, under the same permissions and transactions | planned |
| Object store | the uploaded PDFs, a case's main document and its attachments, for as long as their case exists | a private Cloud Storage bucket (spec 264 (docs/specs/264-google-case-adapters.md)) |
a file, read whole and served to a person, that nothing queries | built, in the backend, on a developer machine and on Google Cloud, where the bucket has no lifecycle rule |
| Document database | derived copies only (ADR-0018 (docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)): the intake's structured result, the loaded business models — one per model version — and per case the compiled business document; a copy of every extraction result, one document per case |
behind its own port; the Firestore emulator in a container on a developer machine (spec 624 (docs/specs/624-firestore-local.md)); Firestore on Google Cloud |
below | the copy of the extraction result built, on a developer machine; removing a deleted case's copies, the loaded models, the compiled document, Firestore on Google Cloud and the intake's structure planned |
Relational and document¶
Relational for the case and everything that belongs to it, its business values included: the
relational database is the store of record (ADR-0018 (docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)). The case changes by transitions that must be atomic: a claim reads and
writes its case under a row lock, and what one transition writes commits in one transaction
(Consistency). The dashboard filters and counts across cases in SQL, a page
belongs to exactly one case and goes with it, the schema is versioned with Flyway, and pgvector puts
the embeddings beside the rows they belong to. That is what a relational database gives and a
document database would make the application rebuild.
Document for derived copies. A loaded business model, a case's business document — its generic
values compiled with the version of the model they were extracted for — and the intake's structure
are each read and written whole and never joined; they nest — groups of fields, each field with its
value, verdict, page and passage; and their shape follows the business model. A document holds that
without a migration per attribute. Each is a copy, rebuildable at any time: the document database
owns no data, and a business model is edited in its LinkML schema in the repository, never in the
document database. It sits behind its own port, so an on-premise installation can replace it
(ADR-0018 (docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)). The extraction result itself is kept whole
in the relational database with its case, which works because nothing queries inside it except the few values the dashboard
filters on.
No event sourcing. The event sequence is not the primary source of state; the rows are. Events go through Spring Modulith's event publication registry, the transactional outbox (8.16.3).
Consistency¶
What is consistent with what, and when. Strong consistency comes from one place, a single transaction in the relational database; whatever runs in another transaction or another store catches up later, and each such step says how.
ACID inside the relational database. What one transition writes to the database — the change of one aggregate, for the case its history entries, the engine's step, and the outbox rows of the events it raises — commits in one PostgreSQL transaction, or none of it does; another aggregate catches up in a transaction of its own (One aggregate per transaction), and which of them are built is the store table's Status column. The constraints the schema declares — keys, foreign keys, not-null — hold for every commit. A commit is durable on the one instance's disk, and only there: there is no backup and no replica (Backup and restore).
The isolation is PostgreSQL's default, read committed: the backend sets no other level. A lost update is kept out by Locking, not by a stricter isolation level: every change reads the case under its row lock, a person's included, and the version check is what Locking adds for people. Read committed takes a fresh snapshot per statement, not per transaction, so a read made of two statements is not one picture: the overview's page and its total are two queries, and a case that changes between them can make them disagree by one.
One instance, no replica. The database is one Cloud SQL instance; read replicas and high
availability are out of scope (spec 102 (docs/specs/102-managed-postgres.md)), and a shared-core
instance is outside Cloud SQL's SLA (ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md) §2).
So there is no stale read and no failover: every read sees the last commit, and when the database is
down, FeeCheck is too, and answers with an error rather than with data from elsewhere. CAP's trade
between consistency and availability arises only between replicas, and so does PACELC's trade
between latency and consistency in normal operation; a read replica or a second region would bring
both in.
Eventual consistency between the stores. There is no transaction across the relational database, the object store, the document database and the queue, and no two-phase commit. Each crossing is ordered so that the relational database stays right, and what a failure can leave elsewhere is named with it:
- Document database — derived, may lag. A copy is written after the case's commit, outside its
transaction. It is behind the case until it is written, and stale for good if the write fails,
which is logged by case ID and exception type only; nothing reads it as the truth, and it is
rebuilt from the relational database. A case's deletion has to reach its copies too
(ADR-0018 (
docs/adr/adr-0018-postgresql-authoritative-document-database-derived.md)); where that stands is the store table's Status column. - Object store — the PDF first on upload, last on delete. The upload puts the PDF before it records the case, and deletes it again when recording the case fails; a crash between the two leaves a PDF no case refers to. A delete marks the case deleted first and removes its PDF after; when that removal fails, the case stays deleted, the failure is logged, and the PDF stays behind. Cloud Storage reads its own writes (strong consistency), so the converter finds the PDF as soon as the case is recorded.
- Queue — no outbox for the upload. The case is committed before its ID is published, and
nothing ties the two together (ADR-0009 (
docs/adr/adr-0009-async-intake-pubsub-bucket-firestore.md) §5). A refused publish fails the case at once. If the backend dies in between, the case stays queued with no message to start it, and its status shows it as failed once the timeout has passed. That failure is worked out when the status is read and never stored: the row stays queued, and the dashboard's counts, which are SQL over the rows, still count it as queued. Pub/Sub delivers a message at least once; a second delivery meets the claim's row lock and lease and finds the case taken or done (Locking). - Events — outbox, at least once. An event goes out from the outbox row written with the change, so it is never lost and never sent for a change that rolled back; it may arrive twice, so every consumer is idempotent (8.16.3, rule 6). A listener runs after the commit, in a transaction of its own, so even inside the one database a module sees another module's change only once its listener has run.
The bucket has no lifecycle rule, since the PDF is kept for its case's lifetime (Retention), so nothing removes either kind of orphaned PDF above. What removes one is open:
TBD
The case in the relational store¶
How the case and what belongs to it are kept in the relational database. The concrete types are in
8.11.3, their tables in
8.19.6. MAC-n is an acceptance criterion of
spec 653 (docs/specs/653-case-persistence-milestone.md).
| Concept | Source | Status |
|---|---|---|
| Access through repositories | MAC-5; ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) |
built for the case through a persistence-shaped record of its row; one repository per aggregate, through save() with a version, planned |
| Aggregates as units of persistence | MAC-1, MAC-6 | planned |
| One aggregate per transaction, the case's history the one exception | ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) §3 |
planned |
| Locking: the pipeline's row lock and lease | spec 457 (docs/specs/457-case-store-postgres.md) |
built |
| Locking: the aggregate's version behind a pipeline write, the safety net | spec 638 (docs/specs/638-generic-extracted-values.md); ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) §3 point 1 |
planned |
| Locking: the case's version for people, the early warning | MAC-3 | planned |
| Locking: the case engine's own optimistic locking | 8.16.3, rule 2 | planned |
| Change history | MAC-4; ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) §3 |
planned |
| Test data and the PoC reset mode | MAC-2 | planned |
| The PDF: kept and served with its case | spec 339 (docs/specs/339-case-api.md) R-10, CA-24 |
built in the backend and on a developer machine; on Google Cloud planned, see the object store's row above |
| The PDF: a seeded case without one | MAC-2 | planned |
Access through repositories¶
Each aggregate has one Spring Data JDBC repository that loads and saves it whole, and no SQL is
written by hand to create, read, update or delete one aggregate
(ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md)). The domain's records
are what is mapped; a transition builds a new record of the case, and the repository's save()
stores that. Only queries across cases — the overview's list and its counts — stay queries of their
own. Every aggregate carries a version: a case's ID is assigned in code, so it is the version — none
yet, or 0 — that tells save() the aggregate is not stored yet and makes it insert rather than
update. The same save() raises the version, refuses an update against a stale one
(Locking) and fills in the auditing columns (Change history).
An update through save() deletes and re-inserts the aggregate's child rows, which is acceptable
for the few rows a case's root carries and the reason the pages are not among them.
Aggregates as units of persistence¶
An aggregate is the unit that is loaded, saved and locked; another aggregate refers to it by its ID. What is written once stays apart from the case, so a transition of the case neither rewrites nor reloads it: a document's pages are written when that document is converted and never again; the extracted values are replaced together when the case is extracted again; the history's entries are written once and never changed, outside any aggregate (Change history).
One aggregate per transaction¶
A transaction writes exactly one aggregate
(ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) §3). What another
aggregate has to do about it follows from a domain event: the event publication registry records the
event in the transaction of the aggregate that raised it, so the registry is the outbox, not an
aggregate, and the event is as durable as the change (8.16.3).
- Conversion saves the document's converted content and publishes that the document is converted; the case then marks its reference to that document converted, in a transaction of its own.
- Extraction saves the case's extraction and publishes
AttributesExtracted, orExtractionRejectedfor an extraction that could not run; the case then advances its stage, in a transaction of its own (spec 638 (docs/specs/638-generic-extracted-values.md)).
So for a moment the case lags its converted document or its extraction, until the event is handled. An event may arrive twice, so every listener is idempotent: handling it again leaves the case as handling it once did. Where one transaction across two aggregates seems needed, the aggregates' boundaries are wrong and are revisited, not this rule.
The one exception is the case's history. It is not an aggregate but the case's append-only change log, and it is written in the transaction that saves the case (Change history). A change and its record must not part, and nothing else needs the same transaction.
Locking¶
Two kinds on the case, one for each kind of writer, and a third inside the case engine. The rule for the two writers is the same for every aggregate of the case, its extraction included:
- The pipeline locks pessimistically. A stage claims a case with a row lock for the transition
and a lease for as long as the stage runs, so two stages never run on one case at once. A
pipeline write locks the case's row inside the store, loads, and saves with what it loaded. The
lease decides which run counts: the run holding the case's current lease wins, and a stale run —
one that does not hold the case's current lease — is refused and saves nothing. The aggregate's version
is a real check behind the lock, the safety net: of two saves made from the same loaded version,
the second is refused (spec 638 (
docs/specs/638-generic-extracted-values.md)). - People lock optimistically. Every change to a case raises its version. A person's action
carries the version that person saw, and a change saved against an older version changes nothing
and is refused with
409. A person's correction of extracted values follows this rule too. Before that, the case screen asks for the case again at intervals and shows a banner when its version changed, so the person is warned before acting. A pipeline step raises the version too, so an open screen also learns of the pipeline's progress. - The case engine locks its own tables optimistically. Two replies, or a reply and a timer, on one case at once meet the engine's optimistic locking, and the loser's delivery is retried (8.16.3, rule 2). It sits beside the row lock and lease: the lease keeps two stages off one case, the engine's version keeps two completions of one step apart.
Neither a channel that pushes the change to the screen instead of polling, nor explicitly locking a case for one person, is part of this concept.
Change history¶
The case collects the domain events of a change in memory. The case store's save writes the case through the case's repository and, in the same transaction, one history entry per collected event through the history's own repository, which only inserts: none, one or several entries per save, and none for a save that raises no event — taking or giving back a lease, starting a step. A refused or failed change leaves no entry, and no use case can save a case and forget its history, because the case store is the only way to save one. An entry references its case by the case's ID and names the case's version, the event, when it happened, and who: a person by the verified e-mail of the session, or "system" for a pipeline step.
The history is kept out of the case's aggregate
(ADR-0019 (docs/adr/adr-0019-spring-data-jdbc-for-the-relational-store.md) §3): no rule of the case
reads its history, and as a child collection Spring Data JDBC would load every entry on every read
of the case and delete and re-insert all of them on every save. It has no version of its own and
is never updated.
Beside the history, the case itself carries who changed it last and when, kept by Spring Data's
auditing on every save, so the overview lists the last change without reading the history. What
changed in detail is not recorded.
Test data and the PoC reset mode¶
While FeeCheck is a proof of concept its data may be lost: a migration may drop and recreate a
table instead of staying compatible with the previous revision, and no backfill is written
(Schema changes, rule 5). So that an instance never starts empty, the
evaluation dataset is seeded when the database is initialised or migrated: on a developer machine
every document of it, on Google Cloud all but the owner documents, which never leave a developer
machine and are not packaged into the deployable.
The PDF¶
A case keeps the uploaded PDF of each of its documents and serves it for as long as the case exists
(spec 339 (docs/specs/339-case-api.md) R-10, CA-24). A seeded case may have none, and a case
without a PDF raises no exception anywhere (MAC-2).
Schema changes¶
The schema is the Flyway migrations under backend/app/src/main/resources/db/migration, applied when
the backend starts, and nothing else creates a table: the outbox's table is a migration too, with
Spring Modulith's own schema initialisation off.
- A schema change is a new
V<n>__<what>.sql, with the next number. An applied migration is never edited: Flyway validates the checksum of every applied one when the backend starts, and a changed or failed one stops the start (spec 102 (docs/specs/102-managed-postgres.md) DB-2). - Migrations only go forward. There is no down migration; undoing a change is another migration.
- Each migration stays compatible with the previous revision, which keeps serving while a new one starts: a deploy runs two revisions side by side for a while, the old one reading the schema the new one has just migrated. A column is added before the code uses it and dropped only after no revision reads it; a rename is an add, a copy and a later drop.
- The migrations of the case store and the outbox also run on H2 in its PostgreSQL mode: the
offline tests load those files with Flyway off (8.4), so they
avoid what only PostgreSQL has. The extension migration runs only on PostgreSQL, and
postgresIntegrationTestis what proves the whole chain. - While FeeCheck is a proof of concept, a migration may drop and recreate a table instead of keeping rule 3: a revision that cannot read the new schema during a deploy is accepted, no backfill is written, and the evaluation dataset is seeded afterwards (Test data and the PoC reset mode). Revisit when real data arrives.
Retention¶
A case is kept until a reviewer or an approver deletes it, or its uploader cancels the intake while
it is queued or converting (spec 567 (docs/specs/567-case-retention.md)). The delete is soft: DELETE
/api/cases/{id} marks the case deleted, by whom and when, and its rows and pages stay. From then on
every read treats the case as unknown and answers 404 case-unknown, and a stage still running on
it stops at its next step; the dashboard's list leaves it out, and its aggregates still count it
(spec 565 (docs/specs/565-dashboard-read-api.md)). Nothing deletes a row: the pages, contract text
included, stay in the table.
The uploaded PDF is the exception: it is removed when its case is deleted or its conversion fails,
and kept for as long as the case exists otherwise, so a person can read it from the case
(spec 339 (docs/specs/339-case-api.md) R-10, CA-24). Where that holds is the object store's row
of the store table above.
Backup and restore¶
Backups are off on the Cloud SQL instance, a working default of
ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md) §7 point 4 that the
Cloud SQL guide (docs/guides/cloud-sql.md) applies; point-in-time recovery is out of scope
(spec 102 (docs/specs/102-managed-postgres.md)), and deletion protection is on. A lost database is not restored: the case's data is synthetic, and the schema is rebuilt by
Flyway on an empty database at the next start. The region and the backup setting stay an
open question.
Connection budget¶
db-f1-micro admits 25 connections. The backend's pool holds three (postgres-cloud-run), the
service runs at most one instance (7.1.2), and a deploy briefly runs two revisions: six connections in the
worst case, which leaves the rest for Cloud SQL Studio, a migration or a person with psql. A
second instance, a larger pool or the case engine's job executor (ADR-0013 (docs/adr/adr-0013-postgresql-on-cloud-sql.md) §6) changes the sum; the
sum is checked before any of them is raised.