by mgsouth · 2y ago · 0 comments
Suppose you've got an "order" table, with a "lineitem" detail table, and a "part" (stock item) master table. What happens if you have, say, two rapid-fire transactions updating the order, with another transaction updating one of the parts sandwiched between the two order updates? Even with the three transactions being processed sequentially, it's possible for all three to wind up being handled in the same clock tick and have the same timestamp. As a result, it's not possible to accurately match the history records for the three tables. An opposite case is when a transaction straddles a clock tick and various updated rows end up with different timestamps.
The author even alludes to the problem. He tackles the transaction-with-multiple-timestamps issue by using NOW() instead of CLOCK_TIMESTAMP() and punts primary/foreign-key issue, in his use-cases, with "... I don’t think it makes sense to have multiple states at a single point in time anyway." Well, experience says it will happen, surprisingly often. If your use-case can't handle the ambiguity then you'll need to do something different.
A more rigorous approach is to include a "version_id" column in each table. If you make it one of the new-fangled UUID7 types then it will be sortable by timestamp. Every table updated in a single transaction should have the same version_id, and every foreign-key reference should also include the foreign version_id. So the "lineitem" table would have "id", "version_id", "order_id", "order_version_id", "part_id", "part_version_id". It is, indeed, a bit more complicated.
EDIT: Normally only the history tables need the foreign-key-version columns; you can code the history-creation triggers to automatically include them. This eliminates most of the additional complexity of using them.
EDIT: More issues with using timestamps: Consider this timeline:
12:34:56.000 Transaction A begins. 12:34:56.001 Transaction B begins, updates a foreign-key table that's needed by trans A, and commits with a timestamp of 12:34:56.001. 12:34:56.002 Transaction A gets around to reading those foreign-key tables, gets the version created at 56.001. Trans A then commits with a timestamp of 12:34:56.000.
So if we look at trans A's history, timestamped at 56.000, we'll wind up matching against the old, stale foreign-key history rows.
You have a race condition here, regardless of whether you use history tables or not, no? It'll probably still be wrong for the user if you update the part first, then do the two transactions, as you now refer to the wrong (a more recent) part version.
I mean, that's the entire reason why Stripe have `products` with multiple `prices` that are "immutable": The price, tax details and so on can't be changed, but they can be archived or set as default. A line item will refer to the price itself, not the product.
If you somehow need to do multiple transactions and your parts aren't immutable, I think you must refer to some immutable history table -- regardless of whether you use the triggers, make an append only table or do something else. If you use the triggers mentioned in the post, you could save the time you looked at the part and do an insert like so:
INSERT INTO line_items (order, part_id, part_history_id)
SELECT ${order_id}, ${part_id}, ph.history_id
FROM parts_history ph
WHERE ph.part_id = ${part_id}
AND ph.systime @> ${as_of_time};
But to be fair, it seems unnecessarily risky. I'd just query the history as of now and use the history ID in the subsequent transaction, or make an append-only part version table and refer to that. BEGIN;
WITH
x_lineitems AS
SELECT li.id, pt.id pt_id, li.qty, (li.qty * pt.cost) ext_cost
FROM (VALUES (${lineitem1}, ${qty1}),
(${lineitem2}, ${qty2})
AS li (id, qty)
x_order AS
INSERT INTO orders (id, total_cost)
SELECT ${order_id},
uuid_generate_v7(),
(SELECT sum(ext_cost) FROM x_lineitems)
RETURNING id, version_id
-- Line items get same version ID as the order.
INSERT INTO line_items (id, version_id, order_id, part_id, qty)
(SELECT xli.id, xord.version_id, xord.id, xli.part_id, xli.qty}
FROM x_lineitems xli, x_order xord);
-- Triggers on orders and line_items fire, still as part of
-- the transaction.
INSERT INTO order_history (id, version_id, total_cost)
SELECT o.id, o.version_id, o.total_cost
FROM orders o WHERE o.id = ${order_id};
INSERT INTO line_items_history
(id, version_id,
order_id, order_version_id,
part_id, part_version_id,
qty)
SELECT l.id, l.version_id,
o.id, o.version_id,
p.id, p.version_id,
l.qty
FROM line_items l JOIN orders o JOIN parts p
WHERE l.order_id = ${order_id}
AND o.id = ${order_id}
AND p.id = l.part_id;
-- And commit everything. If any of the parts rows we referenced
-- change mid-transaction then everything gets rolled back.
COMMIT;1. We forced fully serialized write transactions, because we determined that the users needed simplified semantics they could understand. They need a linear history model for the whole DB, not leaking out a weird graph of MVCC states on different rows. This obviously has some significant performance/scalability implications. Our worldview is more for small, long-tail use cases, so we can scale by having multiple independent databases for different communities and not worry so much about having one large database with optimized write concurrency.
2. We tracked the version timestamps generated by all write transactions in another system table with a uniqueness constraint. The theoretical collision here would abort the second write transaction with a conflict, requiring the application to try again (with a later timestamp). I am not sure it has happened in practical operation given the high precision timestamps used in a modern Postgres deployment.
But, we went wild in other ways: we store model information (much like is in pg_catalog) and have history tracking of that too. This allows different snapshots to add/remove schemas, tables, columns, key constraints, and foreign key constraints, as well as renaming schemas, tables, and columns. The history storage uses JSONB and the model snapshot is needed to properly project this content back into the specific table definition at a given time.
Our systems application is a relatively low-level web service that provides access to a shared database. So we're not really targeting hand-written SQL use cases (though it is feasible to do some custom SQL against the "live" database as a privileged system operator). Instead, our regular use case is that all queries are expressed in our web service API and it generates the SQL queries. Then, an extra parameter can specify a snapshot ID to have the web service API operate read-only over an earlier snapshot. It generates the different SQL necessary to perform the same kind of query over historical data.
And, since our user-visible concept is a web service rather than a raw database, we inject our own web authentication and authorization scheme. So authenticated web users can be tracked for the "who did it" metadata, and we also built our own fine-grained access control scheme that is understood by the web access layer. This policy model is written in terms of the database model and so also gets tracked as snapshots of policy appropriate to one version of the database model. Querying an older snapshot means reconstructing the older model and the older policy that is written in terms of that model.
A final kink is the possibility of needing to amend history. You might need to go back and REVISE the policies applied to older timestamps, because you realize you had a flaw in your policy or because organizational policies have changed and you want to enforce these on any subsequent queries of older data. You might also need to REDACT older data entirely for some kind of confidentiality or compliance reason. This could mean scrubbing historical tuples to make certain fields "null" or even making some historical tuples disappear entirely.