Transactions in Go and MySQL
Use a database/sql transaction to commit an order and its dependent records together, so W3B4 never returns a partially written order.
Learning outcomes
- Explain how an InnoDB transaction keeps an order, its order lines, first order event and outbox row atomic.
- Use
database/sqlto begin, commit and roll back a transaction safely. - Ensure every statement in a transaction uses the same
*sql.Tx, including sqlc queries. - Recognise MySQL duplicate-key error 1062 through wrapped errors using
errors.As.
Placing an order in this API requires several database writes. You create the order, insert its order lines, record the initial PLACED order event and create an outbox row. If the third write fails, the first two must not remain in the database.
W3B4 needs these writes to behave as one unit. A partially written order would be visible to order history without its event or the outbox record needed by the relay. MySQL transactions give you the boundary for this operation.
The all-or-nothing order write
An InnoDB transaction groups database statements into one atomic unit. Either the transaction commits all its changes, or a rollback removes all its uncommitted changes.
For an order, the unit contains four kinds of writes:
- Insert the order with status
PLACEDand version1. - Insert its order lines with their server-calculated prices.
- Insert the first order event, from
''toPLACED. - Insert the outbox row for the relay.
The order lines and order events also depend on the order existing first. Their foreign keys enforce that relationship in MySQL.


The important property here is atomicity. Imagine the order and its two order lines have been inserted successfully, but inserting the first order event fails. The database must not keep the order and its lines.
Without a transaction, each successful statement could commit independently. Your API might return an error while leaving an incomplete order behind. With a transaction, the failed operation prevents the whole unit from committing.
InnoDB transaction guarantees
InnoDB provides the ACID properties:
- Atomicity: all statements in the transaction commit together, or their uncommitted changes are rolled back.
- Consistency: database constraints remain enforced. For example, an order line cannot reference a missing order.
- Isolation: another transaction cannot see this transaction's uncommitted changes.
- Durability: a successfully committed transaction is persisted according to MySQL's durability configuration.
For W3B4, atomicity is the main concern. You do not want an order to exist without its corresponding records.
A successful INSERT inside a transaction does not mean the row is committed. Other transactions cannot treat it as committed data until the transaction commits.
The transaction lifecycle in Go
Go's database/sql package represents an open transaction with *sql.Tx. You start it through *sql.DB, execute statements through the transaction, and finish with either Commit or Rollback.
The usual lifecycle looks like this:
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin transaction: %w", err)
}
defer func() { _ = tx.Rollback() }()
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return fmt.Errorf("execute statement: %w", err)
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit transaction: %w", err)
}Notice where defer appears. You register the rollback immediately after BeginTx succeeds, before executing any statements.
This protects every early return. Suppose the order event insert fails. Your function returns the error, and the deferred rollback runs automatically.
After a successful Commit, the transaction is already finished. Calling Rollback afterward returns sql.ErrTxDone. That is expected, so the deferred cleanup deliberately discards its error.
Transaction options
BeginTx accepts transaction options. Passing nil uses the MySQL server's default transaction settings.
tx, err := db.BeginTx(ctx, nil)In the default MySQL configuration used here, InnoDB uses REPEATABLE READ. You do not need to override the isolation level for the order creation transaction.
The context also matters. Database operations through the transaction use it, allowing cancellation or deadlines to stop work when the request is no longer active.
One connection for every statement
A transaction owns a database connection until it finishes. This is why every statement that belongs to it must use tx, not db.
Consider this mistake:
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
_, err = tx.ExecContext(ctx, insertOrder, args...)
if err != nil {
return err
}
_, err = db.ExecContext(ctx, insertEvent, eventArgs...)The second statement does not participate in the transaction.
*sql.DB manages a pool of connections. Calling db.ExecContext may borrow a different connection from the one held by the open transaction. That statement can commit independently, even if the original transaction later rolls back.
A useful mental model is that *sql.DB manages access to the database, while *sql.Tx represents one active transaction on one connection. The transaction boundary applies only to statements sent through that transaction.
sqlc queries inside a transaction
You do not need to abandon sqlc when working with transactions. Generated query code supports running queries through a transaction using WithTx.
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
qtx := queries.WithTx(tx)
if err := qtx.CreateOrder(ctx, params); err != nil {
return fmt.Errorf("create order: %w", err)
}
return tx.Commit()WithTx returns a new Queries value bound to the supplied transaction. Calls through qtx therefore participate in the same transaction.
The original queries value remains bound to its original database connection provider. If you accidentally use it for one of the writes, that query can execute outside the transaction.
The generated code differs between projects, but the database behaviour is the same. In this week's order implementation, direct database/sql calls make the transaction boundary visible.
Duplicate-key errors
MySQL reports a unique-constraint violation with error number 1062. This is a duplicate-key error.
The order_events table has a unique constraint on event_id. Inserting an event ID that already exists anywhere in the table fails with error 1062, even when the second event belongs to another order.
The MySQL driver exposes this error as *mysql.MySQLError. You can inspect its Number field:
var mysqlErr *mysql.MySQLError
if errors.As(err, &mysqlErr) && mysqlErr.Number == 1062 {
// Handle the unique-constraint conflict.
}The important part is errors.As. Database errors often gain context as they travel through your application.
For example, this preserves the original database error:
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
return fmt.Errorf("insert order event: %w", err)
}The %w verb wraps the original error instead of discarding it. The returned error is now an outer error containing the MySQL error.
errors.As walks that wrapped error chain and finds the underlying value of the requested type. Comparing the returned error directly with == does not perform that search.
There is also an important distinction between database uniqueness and request idempotency. An event ID is unique across the entire order_events table. An idempotency key is scoped to one customer. They represent different identities and must not be treated as interchangeable.
A 409 request_in_progress response in W3B4 represents an idempotency key already claimed by another running request. It is not the HTTP translation of every MySQL duplicate-key error.
Short transaction boundaries
A transaction holds its database connection until it commits or rolls back. It can also hold locks while other database operations wait.
Keep the work between BeginTx and Commit short. Perform validation and pricing before opening the transaction.
For W3B4, menu pricing already exists in the Week 2 configurator. The endpoint can calculate each order line's price and collect selection errors before beginning the database write transaction.
This separation matters under load. If a transaction waits several seconds for another service, its database connection remains occupied for that time. Enough overlapping requests can exhaust the connection pool.
The W3B4 transaction boundary
The order endpoint has two different kinds of work.
The first is request coordination and validation. Redis handles the customer-scoped idempotency key, while the Week 2 configurator calculates the price of each requested line.
The second is the database write. The order, its order lines, its initial order event and its outbox row belong to one MySQL transaction.
Keep these responsibilities separate. Redis and MySQL do not share a transaction, and a MySQL commit does not publish anything to Kafka. The outbox row records the event for the relay to publish after the database transaction has completed.
The next exercise uses this boundary to make checkout retries safe. Understanding which operations commit together is what lets you reason about failures without leaving incomplete orders behind.
Check your understanding
Your code inserts an order and two order lines through tx. The initial order_events insert then fails. What remains in MySQL after the function returns?
References
Everything above is explained on this page; these are where it comes from (Go 1.25 database/sql, go-sql-driver/mysql, MySQL 8.4 InnoDB).