Lawfare Group → Knowledge Institute → Lawfare Academy
← Data Management and SQL for Business
Unit 5
Transactions and controls
Learning objectives
- Explain transactions and controls in your own words.
- Apply the principle to the worked business case.
- Evaluate the answer and identify an assumption that could change it.
Transactions and controls
A transaction groups operations so the database can preserve consistency. Access permissions should follow role and need. Backups must be restorable, and audit records should identify meaningful changes without exposing unnecessary personal data.
Worked example
Recording a payment and updating its allocation should not leave only half the intended change if an error occurs.
Current on-site learning
Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.
Work through the reasoning
Define the business workflow, data, users, system boundary, and failure consequences. For this unit, connect the explanation of transactions and controls to the worked example before answering the practice question.
Check the limits
Test a representative case and identify controls, exceptions, recovery, and the accountable human owner. If the source model and the practical example use different assumptions, state the difference rather than applying the formula or rule mechanically.
Apply it independently
Which feature addresses this consistency problem? Write an answer before opening the model response. Show the calculation or explain the causal or logical steps. Change one material assumption and say whether your conclusion changes. This practice is optional; you can read every part of the course without submitting work.
Advanced investigation: Enforce a cross-row invariant under rollback, retry and contention
A CHECK constraint can validate one row, but a business invariant can span several rows and tables. Total refunds for an order must not exceed its recorded eligible payments in the fictional ledger below. Checking that rule in application memory and inserting later leaves a race: two requests can each observe the same available balance and both consume it. Protect the read-check-write sequence with an appropriate database transaction or atomic conditional write.
SQLite allows multiple readers but serializes writers. BEGIN IMMEDIATE attempts to establish a write transaction before the critical read; another writer can receive a busy result according to configuration and timing. This behavior is engine-specific, so do not transfer a locking claim to another database without checking its isolation semantics. A bounded retry may be appropriate for contention, but the whole operation must remain safe to retry and must not turn a changed request into an apparent duplicate success.
An operation identifier establishes identity. If refund R already exists with the same order and amount, an exact retry can return the established result. If R is reused with different contents, reject the conflict. Equal amounts under different identifiers can be separate legitimate refunds, subject to the aggregate invariant. The uniqueness constraint should enforce identity in the database, while content comparison determines whether a duplicate is a valid retry.
Audit insertion and business mutation belong to the same transaction when the promise is that every mutation has a durable audit record. A test should deliberately fail the audit insertion after inserting the refund and then inspect persisted state. Merely catching an exception does not demonstrate rollback. Some database errors undo only a statement and leave the transaction active, so the application must execute the intended rollback on failure rather than assume every exception ends the transaction.
Reconcile ambiguous completion. If the client times out after commit, a fresh operation ID can create another refund. Reuse the original identity or query its established result. Recovery must separate an uncommitted attempt, a committed event with a lost response and a conflicting request. Preserve authorization at the server boundary as well; an internally correct refund helper does not establish that a caller may access the order.
Worked investigation
A fictional order has 10,000 cents of eligible payments and 3,000 already refunded. Two fresh requests each seek 4,000. A protected first transaction sees 7,000 available and commits, leaving 3,000. The second transaction must then reject 4,000. An unprotected check can let both see 7,000 and produce 11,000 refunded in total. If the first audit insertion fails, its refund must roll back so available capacity remains 7,000. An exact retry after a successful commit returns the recorded event and consumes no additional capacity.
Independent transfer
Write tests for exact retry, changed contents under the same ID, two equal-value distinct events, an over-refund attempt and forced audit failure. Which assertion proves the audit-failure path preserved the invariant?
Transfer reasoning
After forced failure, assert that no new refund or audit row exists and that total refunded amount remains exactly its pre-transaction value. An exception alone is insufficient. For concurrency, verify the persisted sum as well as response outcomes; only one of the competing 4,000-cent requests can commit against 7,000 available. Distinct equal-value events are not deduplicated by amount.
Original Academy expansion: transactions, concurrency and auditability
A transaction groups operations that must succeed or fail together. Atomicity means the transaction's committed effects are all-or-nothing according to the database's guarantees. Consistency concerns preserving declared rules and application invariants. Isolation concerns what concurrent work can observe or interfere with. Durability concerns persistence after commit within the system's documented guarantees. These properties do not remove the need to design correct business operations. A transaction can atomically commit the wrong amount.
Suppose a payment event must be recorded and its allocation created. If the event is saved but the allocation fails, reporting may show unallocated cash. If an application subtracts inventory and then fails to create the shipment, stock can disappear from the system. Put the related operations in a transaction and make error handling explicit. In SQLite, BEGIN, COMMIT, and ROLLBACK manage an explicit transaction; savepoints support nested units of work. A BEGIN transaction is not itself a general nested-transaction mechanism.
Worked investigation: fail between two steps
The lab uses a simpler control table, control_totals, to demonstrate atomicity independently of the sales schema. Begin with two entries, reserve = 100 and available = 100. A fictional transfer of 30 subtracts 30 from available and adds 30 to reserve. The invariant is that their sum stays 200. First begin a transaction, subtract 30, and deliberately raise an application exception before the addition. Roll back. Both entries remain 100. Next perform both updates and commit; available becomes 70 and reserve 130. Verify the invariant after both the failure and success paths.
This does not prove that a transaction prevents every concurrency anomaly. A read-modify-write sequence can use stale information unless its isolation and locking behavior are appropriate. SQLite permits multiple readers but one writer at a time. Applications must handle lock contention and failures rather than treating every retry as harmless. Different engines and isolation levels provide different visibility and conflict rules. A migration plan must revisit these assumptions.
An idempotency key identifies one intended operation across retries. If a payment request times out after the server commits, blindly retrying can record the payment twice. A unique external event identifier lets the system distinguish a retry from a new payment. The rule must be enforced in the trusted data layer. A button being disabled in one browser is not a durable duplicate-prevention mechanism. The key also needs scope: different payment providers might use the same local event string.
Audit history should preserve who did what, when, under which identifier, and why, with suitable access controls. Updating a balance directly can hide the sequence of underlying events. Event records and reconciliations often make the process more inspectable. Do not promise that an ordinary audit table is tamper-proof merely because it is named audit. Its writers, retention, and protection determine its evidentiary value.
Backups and transaction control solve different problems. A transaction protects the integrity of one logical operation under its guarantees. A backup supports recovery from broader loss or corruption. A backup that has never been restored is an untested recovery assumption. Define recovery objectives and test a restoration in an isolated environment. Similarly, parameterized queries protect the boundary between data and SQL syntax; they do not automatically enforce authorization to the requested customer's records. Integrity, security, and recoverability are related but distinct.
Progressive practice
- Foundation: state the invariant for the two-entry transfer and verify both outcomes above.
- Application: explain why a payment retry after a timeout can create a duplicate without a stable idempotency identifier.
- Transfer: a database update succeeds but sending a confirmation email fails. Explain why rolling back a later transaction cannot unsend an email and describe the need for a reliable delivery workflow.
- Critique: an application concatenates a customer-supplied account string into SQL. Explain the separate roles of parameterization and authorization.
Worked reasoning for the practice
The sum remains 200 after a rollback and after the committed transfer. A timeout describes what the caller observed, not whether the server committed. A stable unique operation identifier supports recognizing the same request on retry. External messages are not normally part of the database's atomic transaction; a durable pending-message record and a retryable delivery process can coordinate them while accounting for possible duplicate delivery. Parameterization keeps supplied values from becoming executable SQL syntax. Authorization verifies whether the caller may act on that account. Both are needed.
Reading alignment for this expansion
The earlier introductory links remain background reading. Use the complete current on-site studios; publisher links are optional provenance. The original Academy worked records above are not quotations from those sources.
Complete current conceptual preparation
Transactions, secure stewardship and an auditable analytical store
Connect an invariant to a transaction boundary
Atomicity makes the effects inside a transaction succeed or fail together. Consistency concerns preservation of declared constraints and application invariants. Isolation defines interactions among concurrent transactions. Durability concerns persistence after commit within the actual system guarantees. These properties do not establish that the business operation is correct or authorized. An atomic wrong refund is still wrong. The preserved refund case protects a cross-row total, checks replay identity and tests audit failure rather than merely catching an exception.
In SQLite, BEGIN DEFERRED starts an explicit transaction whose write lock may be needed later; BEGIN IMMEDIATE attempts a write transaction at the start. Multiple readers can coexist with one writer. A busy result is a real outcome that a bounded retry policy must handle. BEGIN statements do not nest; use SAVEPOINT and RELEASE or ROLLBACK TO for controlled partial units. Ending a savepoint is not necessarily committing the outer transaction. Other engines and isolation levels differ; do not transplant these details as universal SQL behavior.
A failed statement does not always roll back all prior work. On any operation failure, determine transaction state and execute the intended rollback or justified repair. If a client loses the response after commit, a new command ID can duplicate the effect. Reuse the original operation identity and compare canonical contents with the established result. If the same ID arrives with a changed amount, report a conflict rather than a replay. Keep command, effect and required audit entry in one atomic boundary. External email or a remote payment provider is normally outside that database transaction; a durable outbox and idempotent downstream delivery can coordinate it, but cannot promise literal exactly-once delivery across arbitrary failures.
Worked capacity and outbox record
Use a separate synthetic account with eligible credits 12000 cents and debits 2000. Available capacity 10000. Two new debit requests of 6000 each must not both be approved against the same initial 10000. After the first valid commit, available 4000 and the second 6000 must fail. If its effect is inserted and the audit entry deliberately fails, rollback must leave debit total 2000 and capacity 10000 for the original state. An identical retry after a successful first commit leaves debit total 8000 and capacity 4000, not 14000 andminus 2000.
Suppose a committed operation also creates outbox message M 1. A delivery worker can send M 1 and crash before recording its acknowledgment. On retry the recipient may receive it again. Preserve a stable message ID and a receiver-side deduplication or harmless replay policy where possible; record delivery attempts and reconcile uncertain outcomes. A report that counts delivery attempts as distinct business debits mixes two event grains. The database transaction should make the business event and pending message durable together, while the delivery contract states its own guarantees.
Security is a set of boundaries and evidence
Confidentiality limits disclosure, integrity protects authorized correctness and availability supports needed access. Authentication establishes an identity, authorization grants permitted actions and auditing records meaningful activity. Grant least privilege for actual duties; a reporting identity should not need unrestricted update authority. Check account/tenant ownership on the trusted server, not only in a filtered browser table. Parameterized SQL separates values from syntax but does not authorize reading another tenant's valid order ID. Avoid logging unnecessary secrets or personal values; logs themselves need controlled access and retention.
Threat modeling starts with assets, actors, entry points and trust boundaries. For a receipt service, threats include forged event identities, unauthorized account access, malicious import text, tampered amounts, credential theft, deleted backups and denial of service. Match each to a control and a test: uniqueness and payload comparison, server-side ownership checks, binding parameters, validated integer/currency domains, protected credentials, isolated recoverable copies and capacity/incident procedures. Encryption in transit protects a connection against relevant interception; encryption at rest protects certain storage exposures. Neither makes an authorized but excessive export appropriate, and keys need their own access and recovery controls.
A practical risk register records scenario, likelihood reasoning, consequence, existing controls, residual risk, accountable owner and next action. Numerical risk scores can help order discussion but should not imply precision unsupported by evidence. A fictional loss estimate 10000 with annual probability.02 gives expected loss 200; a control costing 150 that halves the probability yields expected reduction 100, so expected-value arithmetic alone would not justify it. A mandatory control, severe tail exposure, uncertainty or strategic dependency can still change the decision. State that reason instead of presenting a subjective score as a measured law.
NIST's current Cybersecurity Framework organizes outcomes into Govern, Identify, Protect, Detect, Respond and Recover. Governance sets responsibilities and risk tolerance; identification inventories assets and exposures; protection implements safeguards; detection recognizes events; response contains and investigates them; recovery restores service and learns. A profile describes current and target outcomes, not a certificate that every system is secure. A small database project can map concrete evidence to these functions without claiming compliance or professional approval. This course supplies conceptual and synthetic methods, not a security certification.
Layer safeguards around the actual workflow
A firewall or network segmentation rule limits permitted paths; it does not determine whether a user may refund a particular order. Multi-factor authentication reduces some credential risks but cannot repair a service that trusts a caller-supplied account ID. Patch management addresses known defects under a tested rollout and recovery plan. Malware protection, protected backups and restricted service identities reduce different parts of a ransomware scenario. A phishing-resistant login and staff reporting process can complement technical controls against social engineering. Treat zero trust as continuously justified access to resources rather than a product name that makes internal networks safe by declaration.
Protect secrets outside source code and logs, rotate/revoke them under controlled procedures and test that permissions remain least-privilege. Hashing is not encryption: a one-way digest can help compare integrity or support a properly designed password-storage scheme, while encryption permits recovery with a key. A plain fast hash of a predictable identifier does not anonymize it against enumeration. Pseudonymized records may remain linkable through other fields. Data minimization, purpose limitation and reidentification risk belong in design even when an analytical model never displays names.
Security governance connects policy, standards, procedures and evidence. A policy states required outcomes and authority; a standard defines an enforceable baseline; a procedure describes the actual steps; an audit or review tests evidence against the stated scope. Assign owners for exceptions and time-bounded remediation. Staff, suppliers and managed providers have different responsibilities. A provider's claim about its infrastructure does not establish that this application's public links, permissions or export behavior are correct. Compliance requirements and actual threat reduction overlap but are not identical; report the specific evidence rather than advertising universal compliance.
Recovery must be demonstrated
Recovery point objective(RPO) expresses tolerable lost history; recovery time objective(RTO) expresses tolerable service restoration delay. These are business requirements, not what a backup button guarantees. If the last recoverable snapshot was 06:00 and failure 10:00, up to four hours of later data may be absent without logs or other recovery. Restoring in 30 minutes meets a two-hourRTO but does not meet a one-hourRPO. Test restoration in isolation, verify exact event identities and constraints, and ensure recoverable credentials/configuration as well as data. Transaction rollback, replication and backup solve different problems; a replicated accidental deletion may spread promptly to every replica.
An incident procedure should name detection, containment authority, evidence preservation, communication, recovery validation and review. Do not improvise destructive cleanup while the cause and retained evidence are unknown. Specific notification duties and retention periods depend on applicable law and policy; this unit makes no invented legal deadline. Florida remains the default for contemporary state-law examples, with federal obligations and explicit comparisons separately identified.
From operational events to a warehouse
An operational database emphasizes correct individual transactions. A warehouse integrates curated historical facts for reporting and analysis. A fact table has a declared grain, such as one settled receipt event; dimensions supply descriptive context such as account, product and date. A star layout connects facts directly to dimensions; a snowflake normalizes some dimension hierarchies. Measures have additivity rules: receipt cents can be summed within one currency, account-balance snapshots cannot be summed across days as if they were flows, and rates usually require their numerator/denominator rather than an average of averages.
ETL extracts, transforms and loads; ELT loads into a controlled analytical environment before transformations. Either needs source boundaries, duplicate policy, lineage, quality checks and replay-safe incremental processing. A watermark based only on event time can miss late arrivals. Preserve ingestion time and event identity, allow a reviewed late-arrival/revision policy and compare source-to-target keyed records. Slowly changing dimensions can overwrite a current description or retain versions with valid intervals; choose according to whether reports need current or historical attribution. The original territory example remains the concrete counterexample to silently joining every old event to today's region.
A data mart focuses a governed subset on a department or decision area; it should not silently redefine shared revenue or customer identity. An operational data store integrates relatively current operational information for defined cross-system uses, while a historical warehouse supports a different time horizon. A virtual warehouse or data-federation layer can query remote sources without copying everything centrally. That can reduce duplication while introducing latency, source availability, permission and consistent-snapshot challenges. For example, joining a current receipt source with yesterday's refund source can produce a total that never existed together. Document refresh and snapshot boundaries whether the integration is materialized or virtual.
A data lake can retain raw or lightly processed structured, semi-structured and unstructured objects. Without cataloging, quality, access rules and discoverable lineage, retained objects become difficult to interpret. A lakehouse combines some lake-style storage with managed table/transaction/catalog capabilities, but its guarantees depend on the actual implementation. BI combines governed measures, queries and presentation to support decisions; an attractive dashboard is not a new source of truth. Show the source cutoff, measure definition, unresolved quality flags and drill-down lineage.
Worked warehouse reconciliation
For the independent receipt fixture fromunit 1, raw import rows total 31500 cents, unique events 24000, known-account allocations 20000 and unresolved 4000. A curated receipt fact should retain three distinct event identities and their valid amounts, including the unresolved assignment with an explicit status. The account reporting view can show 20000 assigned plus 4000 suspense. Dropping the unresolved event loses cash; loading every raw replay creates false cash. A daily balance fact would be a different grain and cannot be appended as though it were another receipt.
If a later 4000 allocation resolves suspense, receipt total stays 24000 while account attribution changes. Preserve a versioned correction or event relationship. If the warehouse refresh occurs after a cutoff, a prior published snapshot may remain a valid record of then-known information while a current corrected view differs. Label the distinction and reconcile both; do not overwrite history to hide changes.
Optional progressive practice
Guided model: a race and a failed audit
Credits 12000 minusdebits 2000 leave 10000. A first 6000 commit leaves 4000; the second 6000 must fail. If the first audit fails before commit, rollback restores 2000 debits/10000 capacity. Changed fact: the response is lost after commit. An identical operation retry must find the established 6000 event and leave 8000 totaldebits/4000 capacity, not create another effect.
Independent model: recovery targets
A 06:00 snapshot and 10:00 failure imply a four-hour exposure without later recoverable records. A 30 minute restore meetsRTO 2 hours but failsRPO 1 hour. Changed fact: tested transaction logs recover through 09:45. Potential history loss becomes 15 minutes, provided log completeness and restoration are actually verified. A claim that logs exist is weaker than a successful restoration test.
Transfer model: a warehouse is not a deduplication excuse
Retain three unique receipt events totaling 24000 and expose 4000 unassigned. Changed fact: an equal-valued fourth event has a distinct verified external identity. It must remain a separate fact; a DISTINCT amount rule would discard a legitimate receipt. Catalog the grain, idempotency key, late-arrival policy and source-to-target checks rather than trusting a grand total alone.
Unit rubric: 20 points
Four points each for transaction/invariant/retry boundaries; security roles, threat/control evidence and governance; RPO/RTO restoration reasoning; warehouse/lake/BI grain and lineage; and changed-fact reconciliation. Complete model preserves the 12000/2000 capacity state under failed audit, deduplicates exact commands only, gives the recovery limits and preserves 24000 unique receipts with 4000 suspense. No real financial or learner operation is performed.
Optional source summaries: SQLite transactions was read for explicit boundaries, savepoints and reader/writer behavior. NIST Cybersecurity Framework is optional primary provenance for organizing risk outcomes; the register and all financial/recovery scenarios here are original teaching. No framework use is presented as certification, legal compliance or a production security assessment.
Optional analytical-store provenance: OpenStax warehousing, lakes and BI was read to check the assigned scope, including marts, operational and virtual stores. All business scenarios and reconciliation methods here are original on-site teaching. The NIST CSF2.0 primary document confirms its six outcome functions and tailored profiles; use does not certify security.
Developed study chapters
Original explanation, worked analysis and progressive optional practice.
Apply the idea
Recording a payment and updating its allocation should not leave only half the intended change if an error occurs.
Which feature addresses this consistency problem? Explain your reasoning, then identify one changed fact that could alter the conclusion.
Advanced worked record — a separate fictional scenario: A fictional order has 10,000 cents of eligible payments and 3,000 already refunded. Two fresh requests each seek 4,000. A protected first transaction sees 7,000 available and commits, leaving 3,000. The second transaction must then reject 4,000. An unprotected check can let both see 7,000 and produce 11,000 refunded in total. If the first audit insertion fails, its refund must roll back so available capacity remains 7,000. An exact retry after a successful commit returns the recorded event and consumes no additional capacity.
Independent transfer: Write tests for exact retry, changed contents under the same ID, two equal-value distinct events, an over-refund attempt and forced audit failure. Which assertion proves the audit-failure path preserved the invariant?
Expanded transfer investigation: A caller retries a payment after a timeout. What helps prevent recording the same event twice?
Show the calculation or argument, identify the information available at the decision time, and state which assumption supports your conclusion. The four progressive tasks in the Learn stage provide additional practice.
Read the worked reasoning
An atomic transaction. Atomicity treats the grouped change as one all-or-nothing operation. In an independent response, state the given facts, identify the governing relationship, work through the calculation or comparison, and distinguish the conclusion from assumptions that still need evidence.
Advanced transfer reasoning: After forced failure, assert that no new refund or audit row exists and that total refunded amount remains exactly its pre-transaction value. An exception alone is insufficient. For concurrency, verify the persisted sum as well as response outcomes; only one of the competing 4,000-cent requests can commit against 7,000 available. Distinct equal-value events are not deduplicated by amount.
Expanded transfer reasoning: The server can recognize the same intended operation across retries.
Progressive practice reasoning: The sum remains 200 after a rollback and after the committed transfer. A timeout describes what the caller observed, not whether the server committed. A stable unique operation identifier supports recognizing the same request on retry. External messages are not normally part of the database's atomic transaction; a durable pending-message record and a retryable delivery process can coordinate them while accounting for possible duplicate delivery. Parameterization keeps supplied values from becoming executable SQL syntax. Authorization verifies whether the caller may act on that account. Both are needed.
Check understanding
After subtracting a transfer amount, the application fails before adding it to the other account. What should the lab transaction do?
- Commit the subtraction because it ran first
Feedback
Incorrect. Statement order does not make a partial transfer valid.
- Treat a later backup as an immediate atomic rollback
Feedback
Incorrect. Backups and transaction atomicity solve different problems.
- Roll back both changes in that transaction
Feedback
Correct. The failed logical operation should not leave a partial transfer.
Further reading
Required teaching and complete optional models are supplied on LawfareGroup.com. Publisher and primary links are optional provenance or further reading. Florida is the contemporary state-law default; federal rules and explicitly comparative accounting frameworks are distinguished. Independent subject review and observed human learner testing remain pending.
- Complete on-site teaching — Transactions, secure stewardship and an auditable analytical store
- SQLite — Transactions
- Academy — Runnable business data investigations
- Introduction to Computer Science — 8.5 Data Warehousing, Data Lakes, and Business Intelligence
- Introduction to Computer Science — 14.1 Cyber Resources Management Frameworks
- Introduction to Computer Science — 14.2 Cybersecurity Deep Dive
- Introduction to Computer Science — 14.3 Governing the Use of Cyber Resources