Backend Boilerplates go Advanced New

Go Event Sourcing Store

Minimal append-only event store in Go backed by a Postgres table.

go
type Event struct {
    ID          int64
    AggregateID string
    Type        string
    Data        json.RawMessage
    OccurredAt  time.Time
}

func AppendEvent(db *sql.DB, aggID, evtType string, data any) error {
    payload, _ := json.Marshal(data)
    _, err := db.Exec(
        `INSERT INTO events (aggregate_id, type, data) VALUES ($1,$2,$3)`,
        aggID, evtType, payload,
    )
    return err
}

func LoadEvents(db *sql.DB, aggID string) ([]Event, error) {
    rows, _ := db.Query(`SELECT id,aggregate_id,type,data,occurred_at FROM events WHERE aggregate_id=$1 ORDER BY id`, aggID)
    var events []Event
    for rows.Next() {
        var e Event
        rows.Scan(&e.ID, &e.AggregateID, &e.Type, &e.Data, &e.OccurredAt)
        events = append(events, e)
    }
    return events, nil
}

Prerequisites

  • Go >= 1.21
  • PostgreSQL

Pro Tips

  • → Add a snapshot table to avoid replaying thousands of events.

Was this module useful?

Share your experience — it helps the team improve.

Leave Feedback

Commercial Licensing

Acquire a production access token or template license for enterprise deployment.

Module Info

Language
go
Level
Advanced
Read time
6 min
Published
Aug 2026
License
Commercial License

Newsletter

New modules every week, directly to your inbox.