Skip to content

Use cases

A use case is one business operation: place an order, cancel a booking, approve an invoice. The Go SDK expresses it as a value with named phases and applies its result in one database transaction, so that “the row changed” always means “the event, the dispatch jobs and the audit row were written too”. The concept is explained in the write path; this page is the Go API.

An usecaseop.Operation[C, E] has four parts. C is the command type and E is the domain event the operation produces.

Phase Field Required What it does
Validate Validate(ctx, cmd) error No Checks the command’s shape: presence, format, length. No database access.
Authorize Authorize(ctx, cmd) error Yes Resource-level access: ownership, scope, state. Use usecaseop.Public to declare an operation deliberately open.
Execute Execute(ctx, cmd, ec) (Plan[E], error) Yes Loads data, applies business rules, builds the event, and returns a Plan describing the change.
Apply (done by usecaseop.Run) Applies the plan in one transaction.

usecaseop.Run(ctx, uow, op, cmd, ec) runs the phases in this order and stops at the first error. It fails closed: an operation with no Authorize returns INTERNAL USECASE_MISCONFIGURED, as does one with no Execute, and an Execute that returns a nil plan returns USECASE_NIL_PLAN.

Why a plan. Execute cannot write to the database directly. The only thing it can return is a Plan, a sealed interface whose only constructors are Save, Delete, Emit, SaveAll and Sync, and whose only consumer is Run. There is therefore no code path that persists an aggregate without also writing its event and audit row in the same transaction. Validation and authorisation cannot be skipped for the same reason: Run is the thing that calls them.

sequenceDiagram
  participant H as HTTP handler
  participant R as usecaseop.Run
  participant O as Operation
  participant DB as pgx transaction
  H->>R: cmd, ExecutionContext
  R->>O: Validate
  R->>O: Authorize
  R->>O: Execute
  O-->>R: Plan
  R->>DB: Begin
  R->>DB: Persist aggregate
  R->>DB: Write event
  R->>DB: Write dispatch jobs
  R->>DB: Write audit row
  R->>DB: Commit
  R-->>H: committed event

This is adapted from examples/order-service, which runs against a real Postgres.

// The aggregate does not persist itself; its repository does.
type Order struct {
ID string
CustomerID string
TotalCents int64
}
func (o Order) IDStr() string { return o.ID } // usecase.HasID
type OrderRepository struct{}
func (OrderRepository) Persist(ctx context.Context, o *Order, tx *usecasepgx.DbTx) error {
_, err := tx.Inner().Exec(ctx,
`INSERT INTO orders (id, customer_id, total_cents) VALUES ($1, $2, $3)
ON CONFLICT (id) DO UPDATE SET customer_id = $2, total_cents = $3`,
o.ID, o.CustomerID, o.TotalCents)
return err
}
func (OrderRepository) Delete(ctx context.Context, o *Order, tx *usecasepgx.DbTx) error {
_, err := tx.Inner().Exec(ctx, `DELETE FROM orders WHERE id = $1`, o.ID)
return err
}
type PlaceOrderCommand struct {
CustomerID string `json:"customerId"`
TotalCents int64 `json:"totalCents"`
}
// Optional: names the audit row's operation (default: the command's Go type name).
func (PlaceOrderCommand) AuditOperation() string { return "place-order" }
func PlaceOrder(repo OrderRepository) usecaseop.Operation[PlaceOrderCommand, OrderPlaced] {
return usecaseop.Operation[PlaceOrderCommand, OrderPlaced]{
Name: "PlaceOrder",
Validate: func(_ context.Context, cmd PlaceOrderCommand) error {
if strings.TrimSpace(cmd.CustomerID) == "" {
return usecase.Validation("CUSTOMER_REQUIRED", "customerId is required")
}
if cmd.TotalCents <= 0 {
return usecase.Validation("TOTAL_INVALID", "totalCents must be positive")
}
return nil
},
Authorize: usecaseop.Public[PlaceOrderCommand], // the transport already authenticated the caller
Execute: func(_ context.Context, cmd PlaceOrderCommand, ec usecase.ExecutionContext) (usecaseop.Plan[OrderPlaced], error) {
order := &Order{ID: tsid.GenerateWithPrefix("ord"), CustomerID: cmd.CustomerID, TotalCents: cmd.TotalCents}
event := OrderPlaced{
Meta: newMeta(ec, "sales", "order", "placed", order.ID),
OrderID: order.ID, CustomerID: order.CustomerID, TotalCents: order.TotalCents,
}
return usecaseop.Save(order, repo, event), nil
},
}
}

Wiring and the call from an HTTP handler:

sink := outboxpgx.NewSink(outboxpgx.Config{
ClientCode: "acme", // the client's identifier slug; empty = scoped by the credential
ApplicationCode: "orders", // required on audit rows for an application-scoped credential
AuditEnabled: true,
})
uow := usecasepgx.New(pool, sink)
ec := usecase.NewExecutionContext(principalID)
event, err := usecaseop.Run(r.Context(), uow, PlaceOrder(OrderRepository{}), cmd, ec)
if err != nil {
if ue := usecase.AsError(err); ue != nil {
http.Error(w, ue.Message, ue.HTTPStatus())
return
}
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
// event.OrderID is the committed order
Constructor Writes Use for
usecaseop.Save(agg, repo, event) Upsert one aggregate, its event Create and update
usecaseop.Delete(agg, repo, event) Delete one aggregate, its event Delete
usecaseop.Emit(event) The event only A fact with no state change, such as a sign-in
usecaseop.SaveAll(aggs, repo, event) Upsert many aggregates of one type, one summary event One command that touches many rows
usecaseop.Sync(repo, saves, deletes, rollup) Per-row saves and deletes, each with its own event, then a rollup event Bulk upserts whose consumers project the per-row events

The write order inside the transaction is fixed: the aggregate change, the event (or, for Sync, the per-row events then the rollup), the plan’s dispatch jobs, then the audit row.

The repository implements usecasepgx.Persist[A] with Persist and Delete, both receiving the transaction as *usecasepgx.DbTx (tx.Inner() is the pgx.Tx). Put the repository’s behaviour on the repository, not the aggregate. A repository may return a *usecase.Error of kind validation, business_rule, conflict, authorization or not_found for an invariant that can only be checked inside the transaction; it reaches the caller unchanged. Any other error is wrapped as INTERNAL PERSIST (or DELETE).

An event implements usecase.DomainEvent: EventID, EventType, SpecVersion, Source, Subject, Time, PrincipalID, CorrelationID, CausationID, ExecutionID, MessageGroup and ToDataJSON() ([]byte, error). Embed usecase.EventMetadata for the metadata and write ToDataJSON for the payload.

meta := usecase.NewEventMetadata(ec,
usecase.BuildEventType("orders", "sales", "order", "placed"), // orders:sales:order:placed
"orders:sales", // source: {app}:{domain}
usecase.BuildSubject("sales", "order", order.ID)) // sales.order.<id>
meta.MessageGroup = usecase.BuildMessageGroup("sales", "order", order.ID) // sales:order:<id>
  • NewEventMetadata generates the event id (a 13-character TSID), sets the spec version 1.0 and takes the principal, correlation, causation and execution ids from the ExecutionContext.
  • The subject must be domain.aggregate.id (dot separated). The audit row’s entityType is derived from the second part, capitalised, and its entityId from the third.
  • The message group is the ordering key. Events with the same group reach subscribers in order. See ordering.
  • The event id is also the outbox row id and the deduplicationId, so a batch the relay sends twice does not create a second event.
  • ToDataJSON should return a JSON object. It is written as the JSON value itself, not as a string holding encoded JSON.
  • An event may implement outbox.ClientCoded (ClientCode() string) to name the client it belongs to, overriding the sink’s ClientCode.

usecase.ExecutionContext carries the principal id, a correlation id, a causation id, an execution id and the start time.

Constructor Use
usecase.NewExecutionContext(principalID) A new request. The correlation id is a fresh UUID.
usecase.WithCorrelation(principalID, correlationID) Continue a correlation id from the caller.
usecase.FromParentEvent(parent, principalID) A reaction to an event: correlation from the parent, causation set to the parent’s event id.
ec.WithCausation(id) Set the causation id on an existing context.

The audit row requires a principal id: the platform refuses an audit entry without one.

A plan can carry dispatch jobs next to the event. They are written in the same transaction, so a job exists only if the business change committed.

Execute: func(_ context.Context, cmd IssueInvoiceCommand, ec usecase.ExecutionContext) (usecaseop.Plan[InvoiceIssued], error) {
inv, event := /* ... */
export, err := outbox.NewDispatchJob("billing:ledger:export", "https://ledger.example.com/exports").
WithEventID(event.EventID()).
WithJSONPayload(map[string]any{"invoiceId": inv.ID})
if err != nil {
return nil, err
}
notify := outbox.NewDispatchJob("billing:invoice:notify", cmd.NotifyURL).
WithClientCode(cmd.ClientCode).
WithMessageGroup("invoice:" + inv.ID)
return usecaseop.Save(inv, repo, event).Dispatch(export, notify), nil
},

Dispatch returns a new plan; calls accumulate; the plan it is called on is not changed. The job builder is covered in Outbox.

  • Every job is validated before the transaction opens. An invalid job fails the operation as internal DISPATCH_JOB_INVALID with the rule’s text as the message and the job’s position in Details["index"], and nothing is written. Check values that come from the command in Validate with job.Validate() so the caller gets a 400 rather than a 500.
  • A job without a correlation id takes the plan’s event’s. A job that names no client of its own (WithClientCode or WithPlatformClientID) is written with the sink’s ClientCode, unless that is the platform code _platform, in which case the job carries no client and the platform scopes it by the credential.
  • The sink must implement usecasepgx.DispatchJobSink (outboxpgx.Sink does). Otherwise the operation fails with internal DISPATCH_JOB_UNSUPPORTED, again before any write.

When one logical command must write several aggregates, or return something that is not a single event, use usecaseop.TxOperation[C, R] and usecaseop.RunTx. It has the same Validate, Authorize and Execute phases, but Execute receives a transaction-scoped unit of work and returns a custom result R.

op := usecaseop.TxOperation[ShipCommand, ShipResult]{
Name: "Ship",
Authorize: usecaseop.Public[ShipCommand],
Execute: func(ctx context.Context, s *usecasepgx.TxScopedUnitOfWork, cmd ShipCommand, ec usecase.ExecutionContext) (ShipResult, error) {
if r := usecasepgx.CommitScoped(ctx, s, &order, orderRepo, shipped, cmd); usecase.IsFailure(r) {
_, err := usecase.Into(r)
return ShipResult{}, err
}
if r := usecasepgx.CommitScoped(ctx, s, &ledger, ledgerRepo, debited, cmd); usecase.IsFailure(r) {
_, err := usecase.Into(r)
return ShipResult{}, err
}
return ShipResult{OrderID: order.ID}, nil
},
}
res, err := usecaseop.RunTx(ctx, uow, op, cmd, ec)

Every aggregate write inside Execute must go through CommitScoped, CommitDeleteScoped or EmitEventScoped, so that each change carries its event and audit row. For a raw write on the same transaction use s.WithTx(ctx, func(tx pgx.Tx) error { ... }). RunTx commits on success and rolls back on an error or a panic. Prefer a single-event Operation for ordinary create, update and delete.

usecaseop is built on usecasepgx, and you can call it directly where the envelope does not fit:

Function Purpose
Commit, CommitDelete, CommitAll, CommitSync, EmitEvent Open their own transaction and return a sealed usecase.Result[E].
CommitScoped, CommitDeleteScoped, EmitEventScoped The same, inside a transaction opened by Run or RunErr.
usecasepgx.Run(ctx, uow, fn) Open one transaction, call fn, commit on a successful Result, roll back otherwise.
usecasepgx.RunErr(ctx, uow, fn) The same with fn returning an error.
usecasepgx.WithDispatchJobs(jobs...) A CommitOption that adds dispatch jobs to any commit.

usecase.Into(result) turns a Result[E] into (E, error). Prefer the envelope; reach for these only where it does not fit.

Operations return *usecase.Error. Its Kind decides the HTTP status through HTTPStatus():

Constructor Kind Status
usecase.Validation(code, msg) validation 400
usecase.Authorization(code, msg) authorization 403
usecase.NotFound(code, msg) not_found 404
usecase.BusinessRule(code, msg) business_rule 409
usecase.Conflict(code, msg) conflict 409
usecase.Internal(code, msg, cause) internal 500

WithDetails(map[string]any) attaches structured detail. Failures inside the commit are internal errors with the codes TX_BEGIN, PERSIST, DELETE, EVENT_WRITE, DISPATCH_JOB_WRITE, AUDIT_WRITE and TX_COMMIT, wrapping the cause. See Errors.

When the sink has AuditEnabled, each event also writes an AUDIT_LOG row recording who did what.

  • The operation name is the command’s AuditOperation() if it has one, otherwise its Go type name.
  • operationData is the whole command by default; implement AuditData() any to choose what is recorded, or return nil to record nothing.
  • Redaction. Before an audit row is written the command is redacted by usecase.RedactAuditJSON: a key whose name (lower-cased, with _ and - removed) ends in password, passwordhash, secret, secretref, passphrase or token, or equals apikey, privatekey, authorization or cookie, has its value replaced with "***" (null and booleans are kept). Objects and arrays are walked. A command can implement AuditMaskedFields() []string to mask further top-level keys.
  • Enable audit for human-initiated or administrative operations. A busy transactional event stream rarely needs an audit row per event.