
Phê duyệt nhiều cấp, trạng thái, audit logMulti-level approvals, states, audit logs
Chuẩn bị đợt salePreparing for the sale.9 giờ sáng thứ Hai, Lan ở phòng IT của một sàn thương mại điện tử gửi đề nghị mua thiết bị 120 triệu đồng. Trưởng phòng và giám đốc tài chính phải duyệt trước khi đặt hàng.At 9 a.m. on Monday, Lan in an e-commerce company's IT team requests 120 million VND of equipment. Her manager and the finance director must approve before purchasing.
Hãy theo đề nghị mua thiết bị 120 triệu của Lan đi từ trưởng phòng đến giám đốc tài chính: mỗi lần bấm duyệt đều phải đúng người, đúng bước và đúng version. PostgreSQL giữ quyết định, audit và outbox trong cùng transaction; nhánh thông báo chạy riêng để email chậm không giữ chân người duyệt. Sau luồng thành công, thử hai nhánh từ chối và quá SLA để thấy cách hệ thống bảo vệ quyết định và chuyển việc khi người duyệt vắng mặt.Follow Lan's 120-million-VND equipment request from her manager to the finance director: each decision must come from an authorized actor at the right step and version. PostgreSQL commits the decision, audit and outbox together; notifications run separately so slow email never holds up an approver. After the happy path, try rejection and SLA breach to see how the system protects decisions and hands work over when an approver is absent.
1Lan gửi bản nháp 881 trị giá 120 triệu đồng kèm version=1. API kiểm người gửi và trạng thái nháp để không gửi lại một yêu cầu đã chạy.Lan submits draft 881 for 120 million VND with version=1. The API checks ownership and draft state so an in-flight request cannot be submitted again.
Mỗi trạng thái chỉ cho phép một số hành động: không thể duyệt yêu cầu đã REJECTED hay sửa yêu cầu đang IN_REVIEW. Bảng chuyển trạng thái nằm ở một chỗ, không rải if khắp service.Each state allows only certain actions: you cannot approve a REJECTED request or edit one that is IN_REVIEW. Keep the transition table in one place, not as if statements scattered across services.
Mỗi luật (số tiền, phòng ban, loại chi phí) là một mắt xích quyết định có thêm cấp duyệt hay không. Chuỗi được chụp lại vào bảng approval_step lúc gửi, nên đổi luật sau đó không ảnh hưởng yêu cầu đang chạy.Each rule (amount, department, cost type) is a link that decides whether to add a level. The chain is frozen into approval_step on submit, so later rule changes leave in-flight requests alone.
Client gửi kèm version đã thấy. UPDATE … WHERE version = ? trả 0 dòng nghĩa là trạng thái đã đổi; API trả 409 và client tải lại.The client sends the version it saw. UPDATE … WHERE version = ? returning 0 rows means the state has moved on; the API answers 409 and the client reloads.
Các bước cùng cấp có mode ANY_OF hoặc ALL_OF. ANY_OF: một người duyệt là đủ, các bước còn lại thành SKIPPED. ALL_OF: chờ đủ, một người từ chối là dừng.Steps on the same level carry a mode, ANY_OF or ALL_OF. ANY_OF: one approval is enough and the rest become SKIPPED. ALL_OF: wait for everyone; one rejection stops it.
Bảng delegation có khoảng thời gian hiệu lực. Khi kiểm quyền, người được uỷ quyền cũng được duyệt, nhưng audit ghi rõ “u09 thay mặt u05”.A delegation table holds a validity window. The permission check accepts the delegate too, but the audit entry says “u09 on behalf of u05”.
Mỗi lần chuyển trạng thái phát một sự kiện qua outbox; email, chat, webhook là các subscriber độc lập. Gửi mail lỗi không làm rollback quyết định duyệt.Every transition emits an event through the outbox; email, chat and webhooks are independent subscribers. A failed email never rolls back a decision.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
approval_request | id, requester_id, type, amount, department, payload, state, current_level, version, created_at | DRAFT → SUBMITTED → IN_REVIEW → APPROVED · REJECTED · RETURNED; version cho optimistic lockDRAFT → SUBMITTED → IN_REVIEW → APPROVED · REJECTED · RETURNED; version for optimistic locking |
approval_step | id, request_id, level, mode, assignee_id, status, due_at, decided_by, decided_at | Chuỗi duyệt chụp lúc gửi; mode ANY_OF / ALL_OF cho cùng levelThe chain frozen at submit; mode ANY_OF / ALL_OF within a level |
audit_log | id, request_id, actor_id, on_behalf_of, action, from_state, to_state, comment, at | Chỉ INSERT; tài khoản ứng dụng không có quyền UPDATE/DELETEINSERT only; the app's DB role has no UPDATE/DELETE grant |
approval_rule | id, type, department, min_amount, level, approver_role, version | Luật có version; yêu cầu ghi lại version luật đã dùngVersioned rules; each request records which version it used |
delegation | delegator_id, delegate_id, valid_from, valid_to | Uỷ quyền khi nghỉ phépOut-of-office delegation |
ApprovalService.decide (Java) và Service.Decide (Go) là hộp Approval API ở sơ đồ; entity ApprovalRequest cùng audit_log và outbox nằm trong hộp PostgreSQL, và dòng outbox là thứ relay phát sang Event Bus. Mỗi lệnh tải yêu cầu, kiểm version và quyền, áp dụng chuyển trạng thái rồi ghi audit và outbox trong cùng transaction.ApprovalService.decide (Java) and Service.Decide (Go) are the Approval API box in the diagram; the ApprovalRequest entity, audit_log and outbox live in the PostgreSQL box, and the outbox row is what the relay publishes to the Event Bus. Each command loads the request, checks the version and permission, applies the transition and writes audit and outbox in the same transaction.
package com.example.approval;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class ApprovalService {
private final ApprovalRequestRepository requests;
private final AuditLogRepository audit;
private final DelegationService delegation;
private final OutboxRepository outbox;
@Transactional
public void decide(DecideCommand cmd) {
ApprovalRequest r = requests.findById(cmd.requestId()).orElseThrow();
if (r.getVersion() != cmd.expectedVersion()) {
throw new StaleStateException(r.getVersion()); // 409 Conflict
}
ApprovalStep step = r.currentStep();
if (!delegation.canAct(cmd.actorId(), step.assigneeId())) {
throw new AccessDeniedException("not assigned to this step");
}
RequestState from = r.getState();
switch (cmd.action()) {
case APPROVE -> r.approveCurrentStep(cmd.actorId()); // next level or APPROVED
case REJECT -> r.reject(cmd.actorId());
case RETURN -> r.returnForChanges(cmd.actorId());
}
audit.save(AuditEntry.of(r.getId(), cmd.actorId(), step.assigneeId(),
cmd.action(), from, r.getState(), cmd.comment()));
outbox.save(OutboxEvent.of(r.getId(), from, r.getState()));
}
}package main
import (
"context"
"errors"
"fmt"
)
var allowed = map[State]map[Action]bool{
InReview: {Approve: true, Reject: true, Return: true},
Returned: {Submit: true},
Draft: {Submit: true},
}
var ErrStale = errors.New("request changed, reload")
func (s *Service) Decide(ctx context.Context, cmd DecideCmd) error {
return s.tx.Do(ctx, func(tx Tx) error {
r, err := tx.GetRequest(ctx, cmd.RequestID)
if err != nil {
return err
}
if !allowed[r.State][cmd.Action] {
return fmt.Errorf("%s not allowed in %s", cmd.Action, r.State)
}
step := r.CurrentStep()
if !s.delegation.CanAct(ctx, cmd.ActorID, step.AssigneeID) {
return ErrForbidden
}
from := r.State
r.Apply(cmd.Action, cmd.ActorID) // next level, APPROVED, REJECTED or RETURNED
res, err := tx.Exec(ctx, `UPDATE approval_request
SET state = $1, current_level = $2, version = version + 1
WHERE id = $3 AND version = $4`,
r.State, r.CurrentLevel, r.ID, cmd.ExpectedVersion)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrStale // mapped to 409 by the handler
}
if err := tx.InsertAudit(ctx, Audit{RequestID: r.ID, Actor: cmd.ActorID,
Action: cmd.Action, From: from, To: r.State, Comment: cmd.Comment}); err != nil {
return err
}
return tx.InsertOutbox(ctx, "approval.events", Transitioned{r.ID, from, r.State})
})
}| Tự viết state machineHand-written state machine | Workflow engineWorkflow engine | |
|---|---|---|
| Hợp vớiGood for | Vài loại yêu cầu, luồng ổn địnhA few request types with stable flows | Nhiều quy trình, người nghiệp vụ tự vẽ luồngMany processes that business users model themselves |
| Hẹn giờ, SLATimers, SLA | Tự làm scheduler quét due_atYour own scheduler scanning due_at | Có sẵn timer event và escalationBuilt-in timer events and escalation |
| Vận hànhOperations | Chỉ có DB của bạnOnly your own database | Thêm cụm engine, version hoá định nghĩa quy trìnhAn extra engine cluster and versioned process definitions |
| Chọn khiPick it when | Luồng dưới ~10 trạng thái, team nắm rõFewer than ~10 states and the team knows them well | Quy trình dài, nhiều nhánh, thay đổi thường xuyênLong, branching processes that change often |
Hai lệnh cùng đọc version=3 vẫn có thể vượt qua kiểm tra trong bộ nhớ. Dùng UPDATE có điều kiện version, tăng version cả khi chỉ đổi bước duyệt và rollback toàn bộ nếu khớp 0 dòng; đo tỷ lệ 409 và yêu cầu người dùng tải lại thay vì tự gửi lại quyết định.Two commands reading version=3 can both pass an in-memory check. Use a conditional version update, increment it even when only a step changes, and roll back everything on zero matched rows; track the 409 rate and ask users to reload rather than automatically resubmitting decisions.
Callback sau commit vẫn mất thông báo nếu tiến trình chết trước khi gửi. Ghi outbox cùng transaction, cảnh báo khi bản ghi chưa phát lâu nhất quá 5 phút, retry có backoff và dùng event_id để chống xử lý trùng; nếu nhà cung cấp hỗ trợ, gửi cùng khóa idempotency để tránh email trùng sau timeout.An after-commit callback still loses a notification if the process dies before sending. Write the outbox in the transaction, alert when the oldest unpublished row exceeds five minutes, retry with backoff and deduplicate by event_id; where supported, use the provider's idempotency key to avoid duplicate emails after a timeout.
Đặt due_at cho cả hai cấp ngay lúc gửi khiến cấp 2 có thể quá hạn dù cấp 1 chưa duyệt. Chỉ đặt hạn 48 giờ khi cấp đó được kích hoạt, quét mỗi 5 phút và đo độ trễ chuyển cấp; lúc ghi phải khóa request rồi bước theo cùng thứ tự với API, kiểm tra lại trạng thái và hạn trong cùng transaction.Setting due_at for both levels at submission can expire level 2 before level 1 approves. Start its 48-hour deadline only on activation, scan every five minutes and measure escalation lag; when writing, lock the request then the step in the same order as the API and recheck status and deadline in that transaction.
Ngưỡng đổi từ 100 lên 200 triệu không được tự bỏ cấp tài chính của yêu cầu 120 triệu đang chờ. Lưu chuỗi, phiên bản luật và bản chụp nội dung lúc gửi; nếu phải đổi người duyệt, dùng lệnh chuyển giao có kiểm quyền, tăng version và audit thay vì sửa âm thầm.Raising the threshold from 100 to 200 million must not silently remove finance approval from an in-flight 120-million request. Store the chain, rule version and submitted payload snapshot; if reassignment is necessary, use an authorized command that increments the version and writes an audit entry.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
Cả hai gửi cùng version. Transaction commit trước thắng và tăng version; transaction sau cập nhật 0 dòng, nhận 409 và thấy trạng thái mới. Không có kết quả nửa vời.Both send the same version. The first commit wins and bumps the version; the second updates 0 rows, gets 409 and sees the new state. There is no half-applied outcome.
Không đổi. Chuỗi duyệt đã được chụp vào approval_step lúc gửi và request ghi version luật đã dùng. Luật mới chỉ áp dụng cho lần gửi sau.Nothing changes. The chain was frozen into approval_step on submit and the request records the rule version. New rules apply only to later submissions.
Chỉ cấp quyền INSERT cho tài khoản ứng dụng, có thể thêm cột hash nối chuỗi với dòng trước, và định kỳ xuất ra kho lưu trữ chỉ-ghi-một-lần.Grant the app role INSERT only, optionally add a hash column chained to the previous row, and export periodically to write-once storage.
Quét bằng FOR UPDATE SKIP LOCKED và cập nhật due_at trong cùng transaction; instance khác hoặc bỏ qua dòng bị khoá, hoặc thấy due_at đã ở tương lai.Scan with FOR UPDATE SKIP LOCKED and update due_at in the same transaction; other instances either skip the locked row or see a due_at in the future.
Phím 1–4 để chọn đáp án, Enter để kiểm tra.Press 1–4 to choose an answer, Enter to check.
Ôn tập ngắt quãng (spaced repetition): thẻ được lặp lại sau 1 → 3 → 7 → 14 → 30 ngày để củng cố trí nhớ dài hạn.Spaced repetition: cards are repeated after 1 → 3 → 7 → 14 → 30 days to build long-term memory.