
Ai sửa gì, trước/sauWho changed what, before/after
Chín giờ mở bánThe nine o’clock sale.9:00, sàn thương mại điện tử bắt đầu đợt sale; Lan sửa giá sản phẩm 42 từ 1.190.000 lên 1.290.000 đồng. Đội hỗ trợ cần biết ai đã đổi gì khi khách thắc mắc.At 09:00, an online marketplace opens its sale; Lan changes product 42 from VND 1,190,000 to VND 1,290,000. Support needs to know who changed what when customers ask.
Hãy theo chân Lan sửa giá lúc 9:00: lưu được giá mới thì cũng phải giữ được bằng chứng, ngay cả khi service dừng đột ngột. PostgreSQL commit thay đổi và outbox cùng lúc; relay cùng Audit Writer đưa sự kiện sang lịch sử chỉ cho phép thêm mới, nên màn hình tra cứu có thể cập nhật trễ. Chạy luồng sửa giá trước, rồi thử Kafka timeout, tra lịch sử và sửa trái phép để thấy từng lớp bảo vệ làm việc.Follow Lan’s 09:00 price edit: saving the new price must also preserve evidence, even if the service crashes. PostgreSQL commits the change and outbox together; the relay and Audit Writer deliver it to append-only history, so the history screen can lag behind. Start with the price edit, then try a Kafka timeout, a history lookup, and a tamper attempt to see each safeguard at work.
1Lan sửa giá sản phẩm 42 khi mở sale; ProductAdminService.changePrice lấy actor từ phiên đăng nhập để không ai giả danh bằng request body.Lan edits product 42 at sale opening; ProductAdminService.changePrice takes the actor from the authenticated session so a request body cannot impersonate someone else.
Tầng service biết actor, lý do và tên hành động (PRICE_CHANGED) nên audit có ý nghĩa nghiệp vụ. JPA entity listener (@PostUpdate, Hibernate Envers) tự động nhưng chỉ thấy cột, không thấy ý định. Trigger DB bắt cả lệnh SQL tay nhưng không biết user ứng dụng. CDC (Debezium) đọc WAL, không đụng code, cũng thiếu actor nếu không có cột updated_by.The service layer knows the actor, the reason and the action name (PRICE_CHANGED), so entries carry business meaning. JPA entity listeners (@PostUpdate, Hibernate Envers) are automatic but see columns, not intent. DB triggers catch manual SQL too but do not know the application user. CDC (Debezium) reads the WAL without touching code, and also lacks the actor unless there is an updated_by column.
Gửi Kafka sau commit thì service có thể chết giữa chừng; ghi audit bằng @Async thì mất khi process dừng. Ghi audit_outbox trong cùng transaction, relay đẩy sau, Audit Writer idempotent theo event_id. Hệ thống nhỏ có thể INSERT thẳng audit_log trong transaction.Publishing to Kafka after commit can die halfway; an @Async audit write is lost when the process stops. Write audit_outbox in the same transaction, let a relay publish it, keep the Audit Writer idempotent on event_id. A small system can simply INSERT into audit_log inside the transaction.
Audit chụp nguyên đối tượng sẽ chép cả mật khẩu băm, số thẻ, token. Dùng danh sách trường cần che (password, card_number, national_id, token) áp lên cả before và after; số thẻ chỉ giữ 4 số cuối. Audit được giữ 7 năm nên rò rỉ ở đây rất lâu dài.Snapshotting the whole object copies password hashes, card numbers and tokens. Apply a mask list (password, card_number, national_id, token) to both before and after; keep only the last 4 digits of a card. Audit data lives for 7 years, so a leak here lasts a long time.
Tách audit_writer (INSERT/SELECT) và audit_reader (SELECT), không dùng owner cho ứng dụng; trigger chặn UPDATE/DELETE khi còn bật nhưng owner có thể tắt nó. Hash = sha256(prev_hash ‖ nội dung) chỉ phát hiện viết lại đáng tin khi đối chiếu với mốc neo ngoài DB. Mỗi chuỗi cần xử lý tuần tự và cập nhật đầu chuỗi cùng transaction với INSERT; bản trùng không được làm tiến đầu chuỗi.Separate audit_writer (INSERT/SELECT) from audit_reader (SELECT), and never use the owner for the application; the trigger blocks UPDATE/DELETE while enabled, but the owner can disable it. Hash = sha256(prev_hash ‖ content) reliably detects rewriting only when checked against an external anchor. Serialize each chain and update its head in the same transaction as the INSERT; duplicates must not advance the head.
3 triệu dòng mỗi ngày là khoảng 1 tỉ dòng mỗi năm. Chia partition theo tháng (pg_partman tạo trước), truy vấn luôn có khoảng thời gian để PostgreSQL bỏ qua partition không liên quan. Hết hạn lưu thì DETACH và DROP cả partition, hoặc xuất sang S3 Glacier trước khi xoá.3 million rows a day is about a billion rows a year. Partition by month (pg_partman creates them ahead), and always query with a time range so PostgreSQL prunes the other partitions. When retention ends, DETACH and DROP the whole partition, or export it to S3 Glacier first.
Lưu cả đối tượng dễ đọc nhưng tốn chỗ và dễ dính trường nhạy cảm. Lưu phần khác biệt (các trường đã đổi) gọn hơn, đủ để trả lời “ai đổi gì”. Cột JSONB cho phép thêm trường mới mà không đổi schema.Storing whole objects is easy to read but costs space and drags in sensitive fields. Storing the diff (changed fields only) is compact and enough to answer “who changed what”. A JSONB column lets new fields appear without schema changes.
| BảngTable | Cột chínhKey columns | Ghi chúNotes |
|---|---|---|
audit_log | id, event_id, actor, action, entity_type, entity_id, before jsonb, after jsonb, ip, at, prev_hash, hash | PARTITION BY RANGE (at) theo tháng; unique(event_id, at); index (entity_type, entity_id, at DESC) và (actor, at DESC)PARTITION BY RANGE (at), monthly; unique(event_id, at); indexes (entity_type, entity_id, at DESC) and (actor, at DESC) |
audit_outbox | event_id, payload jsonb, created_at, published_at | Ghi cùng transaction với thay đổi nghiệp vụ; relay đánh dấu published_atWritten in the same transaction as the business change; the relay sets published_at |
product | id, name, price, updated_by, updated_at, version | Bảng nghiệp vụ; updated_by giúp CDC biết actor nếu dùng DebeziumThe business table; updated_by gives CDC an actor if Debezium is used |
db roles | audit_writer: INSERT, SELECT · audit_reader: SELECT · app: không có quyền trên audit_log | Không role nào của ứng dụng có UPDATE hay DELETENo application role has UPDATE or DELETE |
ProductAdminService (Go: ProductAdmin) là hộp Catalog / Order Service ở sơ đồ: chụp giá trị trước, che trường nhạy cảm bằng AuditEvent.mask và ghi audit_outbox trong cùng transaction với UPDATE vào PostgreSQL. AuditWriter.Handle trong file Go là hộp Audit Writer đọc từ Kafka và nối chuỗi hash; audit_log.sql định nghĩa hộp audit_log: partition theo tháng, chỉ cấp INSERT/SELECT và trigger chặn UPDATE/DELETE.ProductAdminService (Go: ProductAdmin) is the Catalog / Order Service box in the diagram: it snapshots the old value, masks sensitive fields with AuditEvent.mask and writes audit_outbox in the same transaction as the UPDATE in PostgreSQL. AuditWriter.Handle in the Go file is the Audit Writer box that consumes Kafka and extends the hash chain; audit_log.sql defines the audit_log box: monthly partitions, INSERT/SELECT grants only and a trigger blocking UPDATE/DELETE.
package com.example.audit;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
@RequiredArgsConstructor
public class ProductAdminService {
private final ProductRepository products;
private final AuditOutboxRepository outbox;
private final CurrentRequest request; // actor + ip from the security context
@Transactional
public Product changePrice(long id, BigDecimal newPrice) {
Product p = products.findByIdForUpdate(id).orElseThrow();
Map<String, Object> before = Map.of("price", p.getPrice());
p.setPrice(newPrice);
Map<String, Object> after = Map.of("price", newPrice);
outbox.save(AuditEvent.of(request.actor(), "PRICE_CHANGED",
"product", String.valueOf(id), before, after, request.ip()));
return p; // UPDATE + outbox INSERT, one commit
}
}
record AuditEvent(UUID eventId, String actor, String action, String entity, String entityId,
Map<String, Object> before, Map<String, Object> after, String ip, Instant at) {
private static final Set<String> SECRET = Set.of("password", "cardNumber", "nationalId", "token");
static AuditEvent of(String actor, String action, String entity, String id,
Map<String, Object> before, Map<String, Object> after, String ip) {
return new AuditEvent(UUID.randomUUID(), actor, action, entity, id,
mask(before), mask(after), ip, Instant.now());
}
static Map<String, Object> mask(Map<String, Object> m) {
Map<String, Object> out = new LinkedHashMap<>(m);
out.replaceAll((k, v) -> SECRET.contains(k) ? "***" : v);
return out;
}
}package main
import (
"context"
"crypto/sha256"
"strconv"
"time"
"example.com/audit/auth"
"github.com/google/uuid"
"github.com/shopspring/decimal"
)
var secret = map[string]bool{"password": true, "card_number": true, "national_id": true, "token": true}
func mask(m map[string]any) map[string]any {
out := make(map[string]any, len(m))
for k, v := range m {
if secret[k] {
v = "***"
}
out[k] = v
}
return out
}
type ProductAdmin struct{ tx TxRunner }
func (s *ProductAdmin) ChangePrice(ctx context.Context, id int64, price decimal.Decimal) error {
actor, ip := auth.ActorFrom(ctx), auth.IPFrom(ctx)
return s.tx.Do(ctx, func(tx Tx) error {
p, err := tx.LockProduct(ctx, id) // SELECT … FOR UPDATE
if err != nil {
return err
}
if err := tx.UpdatePrice(ctx, id, price); err != nil {
return err
}
ev := AuditEvent{
EventID: uuid.New(),
Actor: actor,
Action: "PRICE_CHANGED",
Entity: "product",
EntityID: strconv.FormatInt(id, 10),
Before: mask(map[string]any{"price": p.Price}),
After: mask(map[string]any{"price": price}),
IP: ip,
At: time.Now().UTC(),
}
return tx.InsertAuditOutbox(ctx, ev) // same commit as the UPDATE
})
}
// Simplified writer: serialize each chain; commit Kafka offsets after DB commit.
// Store.Insert must atomically append and advance the chain head only on insertion.
func (w *AuditWriter) Handle(ctx context.Context, ev AuditEvent) error {
prev, err := w.store.LastHash(ctx, ev.Chain())
if err != nil {
return err
}
h := sha256.Sum256(append(prev, ev.Canonical()...))
return w.store.Insert(ctx, ev, prev, h[:]) // ON CONFLICT (event_id, at) DO NOTHING
}| Trong service (ghi tường minh)In the service (explicit) | CDC / trigger DBCDC / DB trigger | |
|---|---|---|
| Thông tin có đượcWhat it captures | Actor, hành động nghiệp vụ, lý do, IPActor, business action, reason, IP | Mọi thay đổi cột, kể cả SQL chạy tay; thiếu actor nếu không có updated_byEvery column change, manual SQL included; no actor unless there is updated_by |
| Khả năng sótChance of gaps | Sót nếu một đường ghi quên gọi auditGaps when a write path forgets to call the audit | Không sót thay đổi nào đã vào DBNo committed change is missed |
| Chi phí vận hànhOperational cost | Chỉ code và một bảngJust code and a table | Debezium, Kafka Connect, replication slot phải theo dõiDebezium, Kafka Connect and a replication slot to monitor |
| Chọn khiPick it when | Cần audit có ý nghĩa nghiệp vụ cho người đọcYou need business-level audit people can read | Cần bằng chứng đầy đủ cho mọi thay đổi dữ liệu, kể cả ngoài ứng dụngYou need complete evidence of every data change, even outside the application |
HTTP 200 chỉ xác nhận thay đổi và outbox đã commit; Kafka lỗi có thể khiến lịch sử chậm nhiều phút. Chỉ đánh dấu published_at sau broker ACK, cấu hình producer acks=all và cảnh báo khi tuổi bản ghi outbox chưa gửi vượt 60 giây hoặc consumer lag tăng liên tục trong 5 phút.HTTP 200 confirms the change and outbox commit; a Kafka outage can delay history by minutes. Set published_at only after the broker ACK, configure producer acks=all, and alert when the oldest unpublished outbox row exceeds 60 seconds or consumer lag rises for 5 minutes.
Relay chết sau broker ACK nhưng trước khi đánh dấu outbox sẽ gửi lại cùng sự kiện. Giữ nguyên event_id và at gốc để UNIQUE(event_id, at) loại trùng, tắt enable.auto.commit và chỉ commit offset sau DB commit; bản trùng không được làm tiến đầu chuỗi hash.A relay crash after the broker ACK but before marking the outbox causes redelivery. Preserve the original event_id and at so UNIQUE(event_id, at) deduplicates, disable enable.auto.commit, and commit offsets only after the DB commit; a duplicate must not advance the hash-chain head.
Chỉ che ở màn hình vẫn để token và CCCD nằm trong outbox, Kafka và backup suốt thời gian lưu. Dùng danh sách trường được phép ghi, che đệ quy trước INSERT outbox và kiểm thử cả before/after với payload lồng nhau; đoạn mask minh họa bên dưới chỉ xử lý trường cấp ngoài cùng.Masking only in the UI leaves tokens and national IDs in the outbox, Kafka, and backups for the retention period. Allowlist fields, mask recursively before the outbox INSERT, and test both before and after with nested payloads; the sample mask below handles only top-level fields.
Chủ bảng có thể tắt trigger, còn người kiểm soát DB có thể tính lại cả chuỗi hash. Giữ tài khoản ứng dụng tách khỏi owner, neo hash định kỳ vào kho WORM độc lập và xác minh với mốc đó; xử lý tuần tự mỗi chuỗi để hai writer không cùng nối vào một prev_hash.A table owner can disable the trigger, and someone controlling the DB can recompute an entire hash chain. Separate application credentials from the owner, anchor hashes periodically in independent WORM storage, and verify against those anchors; serialize each chain so two writers cannot append to the same prev_hash.
Mỗi pattern mở bài học tương ứng trong menu Pattern.Each one opens its lesson in the Patterns menu.
@Async chạy sau và ngoài transaction: process chết hoặc thread pool đầy thì dòng audit mất trong khi thay đổi đã commit. Ghi vào outbox trong cùng transaction rồi đẩy bất đồng bộ thì vừa nhanh vừa không mất.@Async runs later and outside the transaction: if the process dies or the pool is full, the audit row is lost while the change is committed. Writing to an outbox in the same transaction and delivering asynchronously is both fast and lossless.
Role ứng dụng không có UPDATE/DELETE và không sở hữu bảng; trigger chặn sửa khi đang bật. Owner có thể tắt trigger, còn người kiểm soát DB có thể tính lại hash, nên phải ký và neo hash định kỳ vào kho độc lập như S3 Object Lock rồi xác minh với mốc đó.Application roles lack UPDATE/DELETE and do not own the table; an enabled trigger blocks edits. The owner can disable the trigger and someone controlling the DB can recompute hashes, so periodically sign and anchor hashes in independent storage such as S3 Object Lock and verify against those anchors.
Partition theo tháng cộng index (entity_type, entity_id, at DESC). Truy vấn có khoảng thời gian nên chỉ chạm vài partition; trong mỗi partition index tìm thẳng tới vài dòng.Monthly partitions plus an (entity_type, entity_id, at DESC) index. The query carries a time range so it touches only a few partitions, and in each one the index goes straight to a handful of rows.
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.