Skip to contentSaltar al contenido
125+ QA and SEO checks per page

Outbox Pattern Implementation in Go

19 min readadvanced
Website QA and SEO audits

14-day free trial

Try SeekerPro free for 14 days.

Full access while you try it · then $15.99/mo · cancel anytime

Start your 14-day free SeekerPro trial →

30-day money-back guarantee · Cancel anytime

Not checking a site today? Turn this topic into a ready to paste AI prompt, free →

Key Takeaways

  • ✓Outbox Pattern runs in O(1) time and O(n) space, in Go as in every other language.
  • ✓database/sql is in the standard library and provides BeginTx, the Tx handle with its own ExecContext and QueryContext, Commit and Rollback.
  • ✓Defer the rollback immediately after beginning the transaction. Rollback called after a successful Commit returns sql.ErrTxDone and is harmless, so the deferred call is safe unconditionally and guarantees that no early return leaves a transaction open.
  • ✓The Go trap: Omitting that deferred rollback is what causes the classic Go outage in this pattern: an early return on an error path leaves the transaction open, the connection goes back to the pool still inside it, and repeating that under load exhausts the pool until every request blocks waiting for a connection that will never be free.
  • ✓A transaction pins one pooled connection for its entire lifetime, so long transactions reduce effective pool size.

What Outbox Pattern actually is

The transactional outbox exists to solve the dual-write problem: you need to change your database and tell another system about it, and there is no transaction that spans both. Write the row and then publish, and a crash in between loses the message; publish and then write, and a crash leaves a message about something that never happened. The outbox removes the second system from the critical path by writing the message into a table in the very same database transaction as the business change, so the two either commit together or roll back together. A separate relay process then reads unpublished rows and pushes them to the broker, marking them sent as it goes. That relay can crash and retry, so delivery is at least once and consumers must be idempotent. What differs between languages is almost entirely the shape of the transaction API, and specifically how easy each one makes it to believe you are inside a transaction when you are not.

Outbox Pattern in Go: what you actually reach for

database/sql is in the standard library and provides BeginTx, the Tx handle with its own ExecContext and QueryContext, Commit and Rollback. The driver is a separate package but the transaction API is standard.

Go implementation

Defer the rollback immediately after beginning the transaction. Rollback called after a successful Commit returns sql.ErrTxDone and is harmless, so the deferred call is safe unconditionally and guarantees that no early return leaves a transaction open.
go
package outbox

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"
)

func PlaceOrder(ctx context.Context, db *sql.DB, orderID, customerID string, totalCents int64) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin: %w", err)
	}
	// ONE LINE, and its absence is the classic Go outage in this pattern:
	// an early return leaves the transaction open, the connection returns
	// to the pool still inside it, and under load the pool is exhausted
	// until every request blocks forever. Rollback after a successful
	// Commit returns sql.ErrTxDone and is harmless, so this is safe
	// unconditionally. The error is discarded ON PURPOSE.
	defer func() { _ = tx.Rollback() }()

	if _, err := tx.ExecContext(ctx,
		"INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)",
		orderID, customerID, totalCents,
	); err != nil {
		return fmt.Errorf("insert order: %w", err)
	}

	payload, err := json.Marshal(map[string]any{"order_id": orderID, "total_cents": totalCents})
	if err != nil {
		return fmt.Errorf("marshal payload: %w", err)
	}

	// SAME transaction: this is the whole pattern.
	if _, err := tx.ExecContext(ctx,
		"INSERT INTO outbox (id, aggregate_id, event_type, payload) "+
			"VALUES (gen_random_uuid(), $1, $2, $3)",
		orderID, "OrderPlaced", payload,
	); err != nil {
		return fmt.Errorf("insert outbox: %w", err)
	}

	return tx.Commit()
}

func RelayBatch(ctx context.Context, db *sql.DB, limit int, publish func(string, []byte) error) (int, error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return 0, err
	}
	defer func() { _ = tx.Rollback() }()

	rows, err := tx.QueryContext(ctx,
		"SELECT id, event_type, payload FROM outbox "+
			"WHERE published_at IS NULL ORDER BY created_at LIMIT $1 "+
			"FOR UPDATE SKIP LOCKED", limit)
	if err != nil {
		return 0, err
	}

	var ids []string
	for rows.Next() {
		var id, eventType string
		var payload []byte
		if err := rows.Scan(&id, &eventType, &payload); err != nil {
			rows.Close()
			return 0, err
		}
		if err := publish(eventType, payload); err != nil {
			rows.Close()
			return 0, err
		}
		ids = append(ids, id)
	}
	rows.Close()
	if err := rows.Err(); err != nil {
		return 0, err
	}

	if len(ids) > 0 {
		if _, err := tx.ExecContext(ctx,
			"UPDATE outbox SET published_at = now() WHERE id = ANY($1)", ids); err != nil {
			return 0, err
		}
	}
	return len(ids), tx.Commit()
}

Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.

Paste your code. Click QA. Get an instant expert-level audit with fixes.

QA My Code Free

The Go-specific trap

Omitting that deferred rollback is what causes the classic Go outage in this pattern: an early return on an error path leaves the transaction open, the connection goes back to the pool still inside it, and repeating that under load exhausts the pool until every request blocks waiting for a connection that will never be free. The service stops serving with no error in the logs beyond timeouts. The idiom that prevents it is one line, and the reason people leave it out is that Rollback returns an error which linters demand you handle, so the conventional form wraps it in a closure that discards the error explicitly. That is deliberate, not sloppy: after a successful commit the error is expected and meaningless.

Performance in Go, beyond the O(1)

A transaction pins one pooled connection for its entire lifetime, so long transactions reduce effective pool size. SKIP LOCKED lets relay workers scale linearly, and marking rows published in one batched update rather than per message roughly halves the round trips. The asymptotic cost is the same in every language, O(1) time and O(n) space describe the algorithm, not the runtime, so these constant factors and allocation patterns are the part that actually differs when you port Outbox Pattern between languages.

Real-World Applications

Outbox Pattern is used extensively in production software: relational databases, NoSQL systems, ORMs, and data pipelines use this pattern for managing data access and consistency. In Go, check whether the standard library or a well maintained package already provides it before you write your own. Understanding Outbox Pattern helps you reason about the tools you use daily and make better architectural decisions in your own projects.

Interview Tips & Practice

Outbox Pattern appears frequently in final rounds at FAANG-level companies and system design interviews. When presenting your solution: (1) clarify the problem constraints before coding, (2) explain your approach verbally including why you chose Outbox Pattern over alternatives, (3) implement step by step with clean variable names, (4) analyze time and space complexity explicitly, and (5) discuss optimizations and trade-offs. Common follow-up questions include: Can you optimize the space complexity? How does this handle concurrent access? What if the input does not fit in memory? Practice variations of Outbox Pattern to build pattern recognition. In Go, demonstrate proficiency with goroutines and channels to show language mastery alongside algorithmic thinking. Companies value candidates who write idiomatic Go code that is both correct and maintainable.

Frequently Asked Questions

Which Go type or library should I use for Outbox Pattern?

database/sql is in the standard library and provides BeginTx, the Tx handle with its own ExecContext and QueryContext, Commit and Rollback. The driver is a separate package but the transaction API is standard.

What is the most common Go mistake when implementing Outbox Pattern?

Omitting that deferred rollback is what causes the classic Go outage in this pattern: an early return on an error path leaves the transaction open, the connection goes back to the pool still inside it, and repeating that under load exhausts the pool until every request blocks waiting for a connection that will never be free. The service stops serving with no error in the logs beyond timeouts. The idiom that prevents it is one line, and the reason people leave it out is that Rollback returns an error which linters demand you handle, so the conventional form wraps it in a closure that discards the error explicitly. That is deliberate, not sloppy: after a successful commit the error is expected and meaningless.

How does Outbox Pattern actually perform in Go?

A transaction pins one pooled connection for its entire lifetime, so long transactions reduce effective pool size. SKIP LOCKED lets relay workers scale linearly, and marking rows published in one batched update rather than per message roughly halves the round trips. Time complexity is O(1) and space is O(n).

Share this article

🔥 Enjoyed this? Share with someone who'd love it

Related Articles

Rather try before you buy?

Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.

Start my 14-day SeekerPro trial

Before paying for Devin, check its student and free-tier options on Noizz.

Is YOUR site's SEO this optimized?

Find out in 60 seconds with a free QA audit.

Free SEO Check

Is your site built to last?

Run a free QA audit and get your Site Health Score in seconds.

Check Your Site Free

No signup required

Thousands of audits runAverage 23-point score improvement95% fix success rateAudit yours

How does your site compare?

Paste your URL below. Get a complete QA report with SEO score, accessibility issues, security checks, and a one-click fix prompt. Free. No signup.

Takes 30 seconds. No signup. Generates a fix-everything prompt.

Explore More Topics

Engagement

0

Reader comments

No account needed. Share what worked, what did not, and what you would add.

Add your take below. A concrete tip, a result or a question helps the next reader most.