2. Event Sourcing vs Audit Logging - Two Histories, Different Responsibilities
Both record what happened. Only one usually defines what the application is now.
I often see audit logging and event sourcing described as two ways of storing history. That description is true, but it misses their most important difference: what the system trusts as its source of truth.
An audit log records an account of operations. An event-sourced application derives its business state from an ordered history of accepted domain events. A revision table solves a third problem: keeping complete versions of a document.
All three can exist in one application. But they are not interchangeable.
This article uses a content publishing API as a running example. An editor writes an article, another user approves it and the system keeps a history. We will first design a conventional audit trail, then explore how event sourcing changes the data model and finally compare both with document revisions.
Diagrams: This package includes 8 PNG figures in the images/ folder, plus the editable Drawdy board: Open Drawdy board. Each figure has a white background, handwritten styling and soft fill colors on native Drawdy elements.
1. The key question - where does current state come from?
Imagine an article whose status is approved.
In a conventional database design, we may read that value from content_entries.status. The database row is authoritative. An audit table can tell us who approved the article and when, but we do not need the audit table to serve the article.
In event sourcing, the authoritative record is a sequence such as:
PostCreated -> PostEdited -> PostApprovedA projection applies those facts in order to produce the current state: approved. The projection may be stored in a table for fast queries, but it can be rebuilt from the event stream.

The main distinction is not whether the records are immutable. It is whether replaying them is the designed way to derive authoritative business state.
2. Audit logging - a record of actions
Audit logging answers questions such as:
- Who approved article 42?
- When did its visibility change?
- Which service account performed an administrative operation?
- What object did the action affect and what was the outcome?
For our content API, the write path is straightforward:
- An authenticated editor requests an approval.
- The application checks authorization and business rules.
- It updates the authoritative content state.
- It records a structured audit entry.
- It commits the required changes together, when they are in the same transactional store.

A simplified PostgreSQL schema might look like this:
CREATE TABLE content_entries (
id uuid PRIMARY KEY,
status text NOT NULL,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE audit_logs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id uuid,
action text NOT NULL,
resource_type text NOT NULL,
resource_id uuid NOT NULL,
request_id text,
outcome text NOT NULL,
details jsonb NOT NULL DEFAULT '{}'::jsonb
);
CREATE INDEX audit_logs_resource_idx
ON audit_logs (resource_type, resource_id, occurred_at DESC);actor_id can be nullable because automated processes may have a separate service identity. In production, identify those actors explicitly rather than treating a missing user as anonymous. Capture authorization context when it is useful and safe. Avoid storing secrets, tokens or unnecessary personal data in details.
The application might write both records inside one transaction:
func ApprovePost(ctx context.Context, db *sql.DB, postID, actorID string) error {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin approval transaction: %w", err)
}
defer tx.Rollback()
result, err := tx.ExecContext(ctx, `
UPDATE content_entries
SET status = 'approved', updated_at = now()
WHERE id = $1 AND status = 'pending'
`, postID)
if err != nil {
return fmt.Errorf("approve post: %w", err)
}
affected, err := result.RowsAffected()
if err != nil {
return fmt.Errorf("read affected rows: %w", err)
}
if affected != 1 {
return errors.New("post is missing or not pending approval")
}
_, err = tx.ExecContext(ctx, `
INSERT INTO audit_logs
(actor_id, action, resource_type, resource_id, outcome)
VALUES ($1, 'approve', 'post', $2, 'success')
`, actorID, postID)
if err != nil {
return fmt.Errorf("write approval audit: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit approval transaction: %w", err)
}
return nil
}This illustrative function assumes the caller already authenticated and authorized the actor. It also assumes valid UUID inputs, an existing pending state and a single PostgreSQL database. A production handler must define how it treats retries, duplicate requests and concurrent approvals. In particular, RowsAffected() == 0 is not enough to distinguish a missing article from an already completed operation.
The important property is that a successful state update and its required audit record either commit together or both roll back. If audit storage is external, this single-database guarantee no longer holds. You need an explicit reliability design, such as a transactional outbox followed by delivery with retries and deduplication.
A limitation: an audit log is not automatically a complete history of business facts. Some unsuccessful attempts may be important for security investigations even though no business row changed. Log those attempts through a deliberate security-logging path; they cannot always share a transaction with a successful business change.
3. Event sourcing - business facts as the source of truth
Now change the requirement. Suppose product behavior depends on every accepted business transition and we need to build new state representations later from those facts.
Instead of treating content_entries.status as authoritative, the application appends immutable domain events:
{"stream_id":"post-42","version":1,"type":"PostCreated","data":{"title":"First draft"}}
{"stream_id":"post-42","version":2,"type":"PostEdited","data":{"title":"Revised draft"}}
{"stream_id":"post-42","version":3,"type":"PostApproved","data":{"approver_id":"user-7"}}These are domain facts: something that the business accepted as having happened. They are different from commands such as ApprovePost, which express an intention and may be rejected.
The command handler validates invariants against the stream's current state, then appends the accepted event. A projection uses those events to build an efficient read model.

A minimal event-store table could use:
CREATE TABLE domain_events (
event_id uuid PRIMARY KEY,
stream_id text NOT NULL,
stream_version bigint NOT NULL,
event_type text NOT NULL,
event_schema_version integer NOT NULL,
payload jsonb NOT NULL,
occurred_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (stream_id, stream_version)
);
CREATE INDEX domain_events_stream_idx
ON domain_events (stream_id, stream_version);The unique (stream_id, stream_version) constraint is part of optimistic concurrency control. Two writers cannot both append version 4 to the same stream. The application should interpret a version conflict and decide whether to reload, retry or return a concurrency error. Simply retrying a command without revalidating its business rules may be incorrect.
This schema is only a starting point. A production event store must also define append atomicity, command idempotency, event ordering, schema evolution, backups and projection checkpoints.
4. Replay - what reconstruction actually means
Replay applies accepted events in order to rebuild state.
For example:
type PostState struct {
Title string
Approved bool
}
type Event struct {
Type string
Title string
}
func Apply(state PostState, event Event) (PostState, error) {
switch event.Type {
case "PostCreated", "PostEdited":
state.Title = event.Title
case "PostApproved":
state.Approved = true
default:
return state, fmt.Errorf("unsupported event: %s", event.Type)
}
return state, nil
}Read PostCreated, PostEdited and PostApproved in stream-version order, applying each one. The resulting state is the projection. A more complete design should model approval reversal, deletion, event schema versions and invariants rather than treating this example as finished domain logic.

Replay has several important limits:
Reconstruction is not rollback. Replaying the same events normally recreates the same state. Undoing a business operation may require a compensating event. Recovering from corruption requires trustworthy source events, backup strategy and correct event handlers.
Replay must not repeat external effects. Sending a welcome email, charging a card or publishing a notification while rebuilding a projection may duplicate an irreversible action. Keep projection logic deterministic and separate from effectful integrations.
Event schemas live for a long time. Old events must remain interpretable. Use explicit event versions and a tested migration/upcasting policy when schemas evolve.
Read models may lag. If projections are asynchronous, an event can commit before a query model reflects it. Specify where read-after-write consistency is required and whether synchronous projection or a stream-version wait is needed.
Performance needs design. Rebuilding a large stream on every request is not practical. Consider snapshots and materialized projections where measurements justify them; do not assume a snapshot replaces the underlying event history.
5. A revision history is not an event store
There is a common third design that looks similar to event sourcing: document version history.
In our content API, each edit can store a complete validated revision. The content entry points to its current revision and, separately, an approved revision:
content_revisions
revision 1: "First draft"
revision 2: "Second draft"
revision 3: "Approved text"
content_entries
current_revision_id -> revision 3
approved_revision_id -> revision 3
audit_logs
editor edited post
reviewer approved postA reader fetches the article through current_revision_id. A revision-history endpoint retrieves revision 1, 2 or 3 directly. An audit endpoint answers who performed the edit or approval.

This design preserves previous content while keeping ordinary reads simple. It does not become event sourcing merely because revisions are append-only.
The decisive test is: if we delete the current content row and keep only the historical records, are those records designed and sufficient to reconstruct all authoritative business state? If not, do not call the history an event store.
Even if snapshots make reconstruction possible for a narrow object, snapshot versioning is still not automatically a domain-event model. A revision records what a document looked like; a domain event describes what the business accepted as having happened.
6. Comparison - the real trade-offs
| Dimension | Event sourcing | Audit logging | Revision history |
|---|---|---|---|
| Main purpose | Derive state from accepted domain facts | Investigate actions and outcomes | Preserve versions of an object |
| Source of truth | Ordered event stream | Usually current business tables | Current row/pointer plus saved revisions |
| Typical records | PostApproved, OrderShipped |
approve, actor, time, outcome |
Revision 1, 2, 3 snapshots |
| Query strategy | Project events into read models | Query indexed audit records | Query versions by object and number |
| Reconstruction | Core design capability | Not a design goal | Can restore saved snapshots |
| Typical granularity | Every state-changing domain fact in the chosen scope | Defined audit-worthy actions | Each saved version |
| Main burden | Evolution, replay, projections, concurrency | Coverage, integrity, access, retention | Storage, version pointers, conflict handling |
| Best fit | History-driven domain model | Security/compliance/traceability | Editorial/document workflows |
A few cautions make this comparison more precise:
- Immutability is an operational goal, not magic. Database privileges, restricted maintenance processes, integrity controls and storage policies determine whether records can really be changed.
- Audit coverage is policy-dependent. Audit logs can be very detailed; event sourcing is not inherently more granular for every possible action.
- An event stream is not automatically a sufficient security audit. Access denied, failed login, administrative reads and infrastructure actions may never become domain events.
- Compliance is jurisdiction- and policy-specific. Deletion, correction, retention and privacy requirements may conflict with naïve indefinite storage. Design redaction, crypto-shredding, minimization or other lawful controls where appropriate rather than promising that nothing can ever be deleted.
7. When should you choose each model?

Choose audit logging when ordinary database rows already represent the business correctly, but operators need accountability and incident investigation. It is often the least complex choice for an existing CRUD-based API.
Choose revision history when users need previous document versions, approvals, comparison or restoration of saved content. This is a natural model for a publishing or content-management API.
Consider event sourcing when the business needs state reconstructed from a complete stream of domain facts; new projections from historical behavior add meaningful value; and the team can support event-version compatibility, replay testing and operational complexity.
A hybrid can make sense. For example, a payment settlement domain could use event sourcing while user access logs, admin actions and article revisions remain in conventional tables. Avoid moving every table to event sourcing just to make an architecture feel consistent.
8. Reliability and security checklist

Before production, ask how the chosen system behaves under failures:
- Atomicity: Can business changes and mandatory audit records commit together? If not, how are missing records detected and repaired?
- Concurrency: Can two writers race? Are stream versions or row state transitions checked atomically?
- Idempotency: What happens when a client retries after a timeout, especially when the first commit may have succeeded?
- Ordering: Which identifier defines the authoritative order within one business entity? Avoid treating wall-clock timestamps as a concurrency protocol.
- Integrity: Who can insert, read or modify history? Are privileged changes separately monitored?
- Retention and privacy: Which fields are sensitive and what retention/deletion rules actually apply?
- Observability: Can you detect failed audit writes, projection lag, replay errors and dead-lettered integrations?
- Recovery: Have you rehearsed restoring the event store, current tables, revisions and related backups?
These questions are more important than choosing a fashionable pattern.
9. A practical starting architecture

For a typical Go + PostgreSQL publishing API, I would begin with:
Content API (Go)
|
+-- content_entries authoritative metadata and pointers
+-- content_revisions immutable saved document versions
+-- audit_logs actor / action / timestamp / outcomePut related writes in one PostgreSQL transaction when necessary. Give the application an explicit authorization layer, a well-defined state machine and request-level correlation IDs. Monitor failed audit writes and decide how you will handle historical records when privacy requirements change.
Only add an event store when a concrete business requirement makes the event history authoritative. The migration is a domain-model decision, not a logging feature flag.
Conclusion
Event sourcing, audit logging and revision history all preserve history, but they answer different questions.
Audit logging asks: Who did what, when and with what outcome?
Revision history asks: What did this document look like before?
Event sourcing asks: Which accepted domain facts brought the system to its current state?
For many systems, clear transactional updates plus audit records and versioned documents are enough. Event sourcing is useful when its ability to reconstruct state from domain facts is truly part of the product's requirements—and when the team is ready to maintain that contract over time.
References and further reading
- Martin Fowler — Event Sourcing
- Microsoft Azure Architecture Center — Event Sourcing pattern
- Microsoft Azure Architecture Center — CQRS pattern
- Go documentation — Executing transactions
- Earlier article on DEV Community — Comprehensive Research: Audit Log Paradigms, Go/PostgreSQL/GORM Design Patterns
Editorial note: The earlier DEV Community post is related background, not a claim that this new article has already been published there.


