Module 06 · Lesson 6.5
Approvals for Consequential Actions
On this page
- What you will learn
- What makes an action consequential
- The approvals table and the flow
- Proposing and deciding in code
- Executing exactly once
- Step-by-step workflow
- Working with an assistant on approvals
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
A bank will not move a large sum because one clerk typed a number. A second person checks it first. The delay is small. The mistake it prevents can be huge. Some actions in your software deserve the same care.
In this lesson you decide which Tidewell actions are consequential, and you build the approval step that sits in front of them. A request is proposed, checked, approved or rejected by a named person, and then carried out exactly once. Nobody can approve their own request, and the database itself enforces that.
What you will learn
- Decide whether an action is consequential, using plain questions about undoing, reach and personal data.
- Design an approvals table and a flow from proposal to a single execution.
- Enforce a two-person rule in both code and a database rule.
- Test approval, refusal and exactly-once execution with real PostgreSQL behaviour.
Before you start
- Completed Integrating an External Service, or have an outbox and a permission table like Tidewell's.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
What makes an action consequential
A consequential action is one whose effects are hard to undo, reach many people, leave your system, or touch personal data. Think of the difference between pencil and pen.
Most actions are pencil. These are pen.
| Question | A yes makes it more consequential |
|---|---|
| Can it be undone? | An email cannot be unsent. A deleted record may be gone for good. |
| How many people does it affect? | Cancelling one booking touches one patient. Cancelling a whole day touches many. |
| Does it leave our system? | Messages and payments go to people and companies we do not control. |
| Does it involve personal data? | Deleting or sending patient data carries data-protection duties (CON-01). |
| Does software decide it by itself? | An automatic trigger, or an assistant's suggestion, has no person who looked. |
Here is Tidewell's list. It comes from the requirements and the permission table from the last lessons.
| Action | Why it is consequential | Proposed by | Approved by |
|---|---|---|---|
| Send a waiting-list offer email (FR-03) | An email cannot be unsent. It promises a slot to a patient. | The system, when a slot is freed | Front desk or practice manager |
| Cancel a clinician's whole day | Many patients are affected at once. | Front desk, practice manager or that physiotherapist | Practice manager |
| Delete a patient record | It cannot be undone, and data-protection duties apply (CON-01). | Front desk or practice manager | Practice manager |
| Send any bulk message to patients | Many people, and it leaves the system. | To be decided | To be decided |
The approvals table and the flow
Every consequential action becomes a row in one table before anything happens. The row says what is wanted, who asked, who decided, and what the state is now. Think of a form in a tray: nothing is done until someone with authority signs it.
-- Consequential actions wait here until a named person with the permission decides.
CREATE TABLE approvals (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
action text NOT NULL CHECK (action IN ('send_waitlist_offer', 'cancel_clinician_day', 'delete_patient_record')),
payload jsonb NOT NULL,
status text NOT NULL CHECK (status IN ('pending', 'approved', 'rejected', 'executed')),
requested_by bigint REFERENCES app_users (id),
decided_by bigint REFERENCES app_users (id),
decided_at timestamptz,
note text,
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT no_self_approval CHECK (decided_by IS NULL OR requested_by IS NULL OR decided_by <> requested_by)
);actionis limited to the three kinds of approval that exist. A new kind needs a new migration.payloadholds the details as JSON, such as which waiting-list entry and which slot.statusmoves frompendingtoapprovedorrejected, and fromapprovedtoexecuted.requested_byis empty when the system proposes.decided_byanddecided_atsay who decided and when.noteholds their reason.- The
no_self_approvalrule is a database check: whoever decides cannot be whoever asked. Code checks it first, with a friendly message. The database is the last line of defence.
- Propose
Person or system
- Validate
Reject bad input early
- Decide
Another person, with a note
- Execute once
Status executed
- Recorded
Who, when, why
Only an approved request can run, and it can run once.
| Status | Meaning | What can happen next |
|---|---|---|
| pending | Waiting for a person. | Approved or rejected. |
| approved | A person agreed. | Executed, or it stays approved if it can no longer run. |
| rejected | A person said no. | Nothing. It is kept as a record. |
| executed | The action was carried out. | Nothing. It can never run again. |
Proposing and deciding in code
Two permissions guard each kind of action. One lets a role request it, and the other lets a role approve it.
Both come from the permission table in the lesson Roles and Permissions. Here is the map from a kind of action to the approving permission.
export type ApprovalAction = "send_waitlist_offer" | "cancel_clinician_day" | "delete_patient_record";
// Who may approve each kind of action. Anyone with the permission, except the person who asked.
const APPROVER_PERMISSION: Record<ApprovalAction, Action> = {
send_waitlist_offer: "approve_waitlist_offer",
cancel_clinician_day: "approve_day_cancellation",
delete_patient_record: "approve_patient_deletion",
};export async function proposeApproval(
db: Db,
requester: Session | null, // null: the system proposes, for example when a slot is freed
action: ApprovalAction,
payload: Record<string, unknown>,
): Promise<number> {
if (requester !== null) {
if (action === "cancel_clinician_day") {
const clinicianId = isPositiveInteger(payload.clinicianId) ? payload.clinicianId : 0;
requirePermissionForClinician(requester, "request_day_cancellation", clinicianId);
} else if (action === "delete_patient_record") {
requirePermission(requester, "request_patient_deletion");
} else {
throw notAllowed("Waiting-list offers are proposed by the system only.");
}
}
const errors = payloadErrors(action, payload);
if (errors.length > 0) throw invalidRequest(errors);
const { rows } = await db.query<{ id: number }>(
`INSERT INTO approvals (action, payload, status, requested_by)
VALUES ($1, $2::jsonb, 'pending', $3) RETURNING id::int AS id`,
[action, JSON.stringify(payload), requester?.userId ?? null],
);
return rows[0].id;
}- A
nullrequester means the system proposes, for example when a cancelled slot is freed. - A person must hold the request permission. A physiotherapist may name only their own day, through
requirePermissionForClinician. - The payload is validated here, when the request is made. A bad request is refused at once and never waits in the queue.
- Values go in as parameters. The payload travels as JSON text and is converted by
$2::jsonb.
export async function decideApproval(
db: Db,
decider: Session,
approvalId: number,
decision: "approved" | "rejected",
note: string,
now: Date,
): Promise<void> {
const found = await db.query<{ action: ApprovalAction; requested_by: number | null }>(
"SELECT action, requested_by::int AS requested_by FROM approvals WHERE id = $1",
[approvalId],
);
if (found.rows.length === 0) throw notFound();
const { action, requested_by } = found.rows[0];
requirePermission(decider, APPROVER_PERMISSION[action]); // is this role allowed to approve this kind?
if (requested_by === decider.userId) throw notAllowed("Nobody can decide their own request."); // two-person rule
const text = note.trim();
if (text.length === 0 || text.length > 500) {
throw invalidRequest([{ field: "note", message: "Give a note of 1 to 500 characters." }]);
}
const { rows } = await db.query<{ id: number }>(
`UPDATE approvals SET status = $2, decided_by = $3, decided_at = $4, note = $5
WHERE id = $1 AND status = 'pending' RETURNING id::int AS id`,
[approvalId, decision, decider.userId, now.toISOString(), text],
);
if (rows.length === 0) {
throw invalidRequest([{ field: "approvalId", message: "This request has already been decided." }]);
}
}What each part does
- It finds the request first. No such request gives 404.
requirePermissionasks whether this role may approve this kind of action. A physiotherapist cannot approve a waiting-list offer.- The two-person rule: if the decider is the requester, the answer is 403 "Nobody can decide their own request".
- A note of 1 to 500 characters is required. A decision with no reason is not a record anyone can use later.
- The
UPDATEonly matches a row that is stillpending. Two people deciding at once, or one person twice, cannot both win.
A. A freed slot: the system proposes a waiting-list offer
propose (slot 3): ok {"approvalId":1}
propose with slotId missing: 400 payload.slotId: Must be a whole number above zero.
execute before any decision: ok "nothing executed"
physiotherapist tries to approve: 403 Your role is not allowed to do this.
front desk approves without a note: 400 note: Give a note of 1 to 500 characters.
front desk approves with a note: ok
front desk decides again: 400 approvalId: This request has already been decided.The bad proposal was refused with the field named. The physiotherapist could not approve.
A decision without a note was refused. A second decision on the same request was refused too.
The two-person rule, with the real database error
Deleting a patient record needs one person to ask and a different person to approve. Here the practice manager asks, and then tries to approve the same request. The test also skips the code and updates the table directly, to prove that the database refuses on its own.
await step("front desk asks to cancel clinician 2's day", () => proposeApproval(db, frontDesk, "cancel_clinician_day", { clinicianId: 2, date: "2026-12-01" }));
await step("physiotherapist asks to delete a record", () => proposeApproval(db, physio, "delete_patient_record", { patientId: 2 }));
await step("practice manager asks to delete a record", () => proposeApproval(db, manager, "delete_patient_record", { patientId: 2 }));
await step("the same manager tries to approve it", () => decideApproval(db, manager, 5, "approved", "Done.", NOW));
await step("front desk tries to approve it", () => decideApproval(db, frontDesk, 5, "approved", "Done.", NOW));
await step("someone skips the code and updates the table", () =>
db.query("UPDATE approvals SET status = 'approved', decided_by = 5, decided_at = $1 WHERE id = 5", [NOW.toISOString()]),
);
await step("front desk files a request instead", () => proposeApproval(db, frontDesk, "delete_patient_record", { patientId: 2 }));
await step("the manager approves it", () => decideApproval(db, manager, 6, "approved", "Request checked with the clinic owner.", NOW));C. Deleting a patient record: two different people
front desk asks to cancel clinician 2's day: ok 4
physiotherapist asks to delete a record: 403 Your role is not allowed to do this.
practice manager asks to delete a record: ok 5
the same manager tries to approve it: 403 Nobody can decide their own request.
front desk tries to approve it: 403 Your role is not allowed to do this.
someone skips the code and updates the table: database refused - new row for relation "approvals" violates check constraint "no_self_approval"
front desk files a request instead: ok 6
the manager approves it: okRead the sixth line closely. The code refused the manager first with a 403. When the test went around the code, PostgreSQL itself refused with the no_self_approval rule.
Front desk could not approve either, because that role holds no approval permission. When front desk filed the request, the practice manager could approve it.
Executing exactly once
Approval is not the end. The action must now run, and it must run once, even if two people press the button together or a job retries. The trick is to claim the request and do the work in the same statement.
// Execute exactly once: the claim (approved -> executed) and the effect (an outbox row) are one statement.
// It claims nothing if the status is not 'approved', or if the entry is gone or the slot has been booked since.
export async function executeWaitlistOffer(db: Db, approvalId: number): Promise<{ outboxId: number } | null> {
const { rows } = await db.query<{ outbox_id: number }>(
`WITH claimed AS (
UPDATE approvals a SET status = 'executed'
WHERE a.id = $1 AND a.status = 'approved' AND a.action = 'send_waitlist_offer'
AND EXISTS (SELECT 1 FROM waiting_list_entries w WHERE w.id = (a.payload->>'waitingListEntryId')::bigint)
AND EXISTS (SELECT 1 FROM slots s WHERE s.id = (a.payload->>'slotId')::bigint)
AND NOT EXISTS (SELECT 1 FROM bookings b WHERE b.slot_id = (a.payload->>'slotId')::bigint AND b.status = 'booked')
RETURNING a.id, a.payload
)
INSERT INTO email_outbox (to_address, subject, body, idempotency_key, status)
SELECT p.email, 'A Tidewell appointment is free',
'A slot with ' || c.display_name || ' is free at ' || to_char(s.starts_at AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI')
|| ' UTC. Book it online, or phone the clinic on 01632 960 123.',
'waitlist-offer-' || claimed.id, 'pending'
FROM claimed
JOIN waiting_list_entries w ON w.id = (claimed.payload->>'waitingListEntryId')::bigint
JOIN patients p ON p.id = w.patient_id
JOIN slots s ON s.id = (claimed.payload->>'slotId')::bigint
JOIN clinicians c ON c.id = s.clinician_id
RETURNING id::int AS outbox_id`,
[approvalId],
);
return rows.length === 0 ? null : { outboxId: rows[0].outbox_id };
}What each part does
- The first part of the query,
claimed, changes the status fromapprovedtoexecuted. It matches only if the status is stillapproved, so a second try matches nothing. - The second part writes the offer into the email outbox from the last lesson. The key is
waitlist-offer-plus the approval id, which is unique. Even a bug could not queue it twice. - The claim and the email row are one statement. If one fails, neither is saved. There is no moment when it is marked executed but no message exists.
- The claim also checks that the waiting-list entry still exists and that nobody has booked the slot since the proposal. Things change between a proposal and a decision, so the check runs again at the last moment.
- A result of
nullmeans nothing was executed. The caller must treat that as an answer, not as an error to hide.
execute: ok {"outboxId":1}
execute again: ok "nothing executed"
outbox: {"n":1,"key":"waitlist-offer-1"}
B. Rejected, and a slot taken in the meantime
front desk rejects: ok
execute a rejected request: ok "nothing executed"
front desk approves (slot 1 was booked meanwhile): ok
execute: ok "nothing executed"The first execute queued one email. The second changed nothing, and the outbox still held one row. A rejected request could not run.
The last request was approved while the slot was free, but another booking took the slot first. So it stayed approved, with nothing sent, for a person to look at.
approvals:
{"id":1,"action":"send_waitlist_offer","status":"executed","requested_by":null,"decided_by":3,"note":"Patient B asked for Thursday-week mornings."}
{"id":2,"action":"send_waitlist_offer","status":"rejected","requested_by":null,"decided_by":3,"note":"Patient B is on holiday."}
{"id":3,"action":"send_waitlist_offer","status":"approved","requested_by":null,"decided_by":3,"note":"Offer it."}
{"id":4,"action":"cancel_clinician_day","status":"pending","requested_by":3,"decided_by":null,"note":null}
{"id":5,"action":"delete_patient_record","status":"pending","requested_by":5,"decided_by":null,"note":null}
{"id":6,"action":"delete_patient_record","status":"approved","requested_by":3,"decided_by":5,"note":"Request checked with the clinic owner."}Every row says who asked, who decided and why. That is the record you want when a patient asks, six months later, why they got that email.
Only the waiting-list offer has an executor here. Cancelling a clinician's day and deleting a record would follow the same shape.
They are larger jobs, with their own rules about what counts as done and what must be kept. Design them with the practice manager and the clinic owner, and do not leave them to a generated guess.
Step-by-step workflow
Step 1: List the consequential actions
Ask the five questions of every action in your requirements. Write down each that gets a yes, and say why.
What you should see: A short list with a reason for each action.
Step 2: Decide who requests and who approves
Use the permission table. Give each step to a role, and make sure no one holds both steps for the same request unless the team has chosen it.
What you should see: A request role and an approve role for each action.
Step 3: Write the approvals migration
Add the table, the status values and the rule that stops self-approval.
What you should see: A table that refuses a request decided by its own requester.
Step 4: Validate at the start
Check the payload when the request is made. Refuse bad input before it waits for a person.
What you should see: A clear error that names the bad field.
Step 5: Require a named person and a note
A decision needs a signed-in person with the right permission, who is not the requester, and a reason.
What you should see: Every decision row has a person, a time and a note.
Step 6: Execute in one statement
Claim the request and do the work together, with a check that the world has not changed since the proposal.
What you should see: A second execution changes nothing.
Step 7: Test the refusals first
Test self-approval, the wrong role, a missing note, a second decision and a second execution. Use synthetic data only.
What you should see: Each refusal has a test that can fail.
- Wrong role
403
- Own request
403 and database rule
- Second decision
Refused
- Second execution
Nothing happens
- Approved once
Effect appears once
Four are refusals. Only one shows the action working.
Working with an assistant on approvals
| Task | Assistant's part | Your part |
|---|---|---|
| Find consequential actions | Reads your requirements and proposes candidates with reasons. | Decide which are real, and take the list to the practice manager. |
| Draft the offer text | Writes a first version of the message for the person to review. | Read it, correct it and approve it. The assistant never sends it. |
| Draft the flow and tests | Proposes the states and the refusal tests. | Check that every refusal has a test and that none is skipped. |
| Approve or execute | Nothing. It never approves, rejects or runs an approved action. | A named person does both, with a note. |
| Decide who approves | Nothing. It guesses. | Record the answer from the owner of the rule. |
Conclusion and your next step
Consequential actions are hard to undo, wide in reach, or sent outside. Tidewell puts every one of them behind an approvals table. Someone proposes, input is validated, a different named person decides with a note, and the action runs exactly once.
Your next step: list the consequential actions in your capstone and write the approval step in front of each. Then move on to Testing, CI/CD and Release, where you turn your criteria into tests that run on every change.
For more on thinking through what could go wrong, try the Threat Model a New Feature prompt, or read STRIDE Threat Modeling with AI: A Step-by-Step Guide.
Reusable prompt
Consequential-action review
Asks the assistant to find actions that need human approval, and to check an approval design for gaps, without writing code or deciding who approves.
You are reviewing which actions need human approval. Do not write code. Do not decide business rules.
Fictional clinic: Tidewell Physiotherapy. Roles: patient, front_desk, physiotherapist, practice_manager. Personal data is held under the clinic's data-protection duties.
Candidate actions from the requirements:
- Send a waiting-list offer email when a slot is freed (the system proposes).
- Cancel a clinician's whole day.
- Delete a patient record.
- Send a bulk message to patients.
- Change one booking on a patient's behalf (front desk can do this directly, and every change is recorded).
Design so far: a request is proposed, validated, approved or rejected by a different named person with a note, and then executed exactly once. A database rule stops anyone approving their own request.
Tasks:
1. For each candidate, answer: can it be undone, how many people it affects, does it leave our system, does it involve personal data. Then say whether it needs approval, and why.
2. List actions that are missing from my candidates, with the reason you suspect each.
3. List ways the approval design could be bypassed or fail, such as a test flag, a second execution or a change between proposal and approval.
4. List the tests you would want, one line each.
5. List every decision that needs a person under "Decision needed", with the role who should decide.Show the reusable template
Replace each {{placeholder}} with your own details.
You are reviewing which actions need human approval. Do not write code. Do not decide business rules.
Context: {{organisation_roles_and_data_duties}}
Candidate actions from the requirements:
{{candidate_actions}}
Design so far: {{approval_design_summary}}
Tasks:
1. For each candidate, answer: can it be undone, how many people it affects, does it leave our system, does it involve personal data. Then say whether it needs approval, and why.
2. List actions that are missing from my candidates, with the reason you suspect each.
3. List ways the approval design could be bypassed or fail, such as a test flag, a second execution or a change between proposal and approval.
4. List the tests you would want, one line each.
5. List every decision that needs a person under "Decision needed", with the role who should decide.Expected output and limitations
A short table answering the four questions for each candidate with a yes or no on approval, a list of missing actions, a list of bypass risks, one-line tests, and a Decision needed list with roles.
1. Candidates
Waiting-list offer email : cannot be undone; one patient; leaves the system; personal data -> approval.
Cancel a clinician's day : hard to undo; many patients -> approval.
Delete a patient record : cannot be undone; personal data -> approval.
Change one booking : can be reversed; one patient; recorded (FR-05) -> no approval.
2. Possibly missing
- Staff account changes (switching an account off) - Suggestion, unconfirmed.
3. Risks
- A "skip approval" setting used in tests that is left on in production.
- The slot is booked between the proposal and the approval.
5. Decision needed
Which roles may send a bulk message? Role: practice manager.
May the clinic later let the system send offers without approval? Role: clinic owner.Limitations to keep in mind
- The assistant reasons from your list. It does not know the clinic's real risks, so a person must confirm each decision.
- It may suggest approvals for everything. Too many approvals slow the clinic down, so keep them for actions that earn them.
- A review is not a test. Only the refusal tests, run against a real database, show that the rules hold.
Common errors and how to fix them
The same person can request and approve an action.
Why it happens: The approval step checked the role but not who asked.
Fix: Compare the decider with the requester in code, and add a database rule as a last line of defence.
An approved action can run twice.
Why it happens: The status was checked, then updated in a separate step, so two runs slipped through.
Fix: Claim the request and do the work in one statement, matching only status approved.
A test flag that skips approval reaches production.
Why it happens: It made demos and tests easier.
Fix: Never add a bypass flag. Tests should create real approvals with fake people, and the stub sender should receive the result.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Approvals for Ferngate's reorders
Ferngate Cycle Repairs wants the system to email a supplier when stock is low. Decide which actions are consequential, design who requests and who approves, and list the tests. The owner is the only person who knows the supplier terms.
You will need
- Candidate actions: email a reorder to a supplier; adjust a stock count to zero; delete a part from the catalogue; record a part taken for a job.
- Note: the low-stock threshold is still "to be agreed" with the owner.
- Note: the workshop has one owner and three mechanics.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Recording a part taken for a job is frequent and reversible. Think about whether approval there would help or only slow the workshop down.
- An email to a supplier may commit the shop to buy. Which of the five questions does that touch?
Show a model answer
A strong answer marks the supplier email as consequential, because it leaves the system and may commit money. Deleting a catalogue part is also consequential. Recording a part for a job is not, since it is frequent and reversible, and approvals would only slow the workshop. Adjusting stock to zero is a judgement call, and the answer should raise it as a question for the owner. A mechanic or the system proposes the reorder and the owner approves it. If the owner is also the requester, the two-person rule leaves a real choice: a mechanic files the request, a second approver is named, or a waiting period and written record are used. The tests include self-approval, the wrong role, a missing note, a second decision and a second execution. The threshold stays open.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. A single booking change can be reversed, affects one patient, stays inside the system and is recorded under FR-05, and FR-04 lets front desk do it directly. An email cannot be unsent and a deletion cannot be undone, which is why the other two are tempting to leave without a second look but must have approval.
Show the answer and explanation
Answer: B. Only one statement can change the status from approved to executed, so only one run finds a row to claim. Disabling a button helps one browser but not two people, and the assistant is not part of the running system at all.
Show the answer and explanation
Answer: B. Code checks can be missed by a new endpoint, a script or a bug. A database rule applies to every route into the table. Speed is not the reason, and code checks can certainly be tested, as the lesson shows.
Frequently asked questions
What is a two-person rule?
It means that one person asks for an important action and a different person approves it. A single mistake or a single dishonest person cannot cause the action alone. Banks and many other organisations use it for large or irreversible actions.
Which actions need human approval?
Actions that are hard to undo, affect many people, leave your system or involve personal data. Sending an email, deleting a record and spending money are common examples. Small reversible actions do not need it, because approval costs time.
How do I make sure an action runs only once?
Claim it and do the work in a single step, so only one attempt can succeed. In PostgreSQL, a single statement with a WITH clause can update the status and insert the result together. A second attempt then finds nothing to claim.
Should an AI assistant be allowed to approve or send things by itself?
Not for consequential actions. An assistant can draft a message or propose an action. A named person should read it and approve it, and the system should record who did. This matters even more when an assistant can call tools that act in the real world.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Transaction Authorization Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Why important actions need extra confirmation, and how to design it.
- Authorization Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Least privilege and separation of duties.
- 5.5. Constraints(opens in a new tab)
PostgreSQL Global Development Group · Official documentation · CHECK rules, as used to stop self-approval.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.