Golang Database Patterns: Install, Source and Security

Golang Database Patterns

Published by codewithkrushnal in agentic

Audit unavailable3 installs

What this skill does

>

Add Golang Database Patterns to your agent

Review the source and files first. When you are ready, copy the prompt instruction or use the CLI command supported by your environment.

Install with a prompt

Paste this into a compatible coding agent:

add this skill "golang-database-patterns" from https://github.com/codewithkrushnal/agentic

Install with the CLI

Run this command in a controlled environment after reviewing the repository:

npx skills add https://github.com/codewithkrushnal/agentic --skill golang-database-patterns

Skill instructions

Go Database Patterns

When to Invoke

  • Writing or reviewing repository, store, or data-access layer code
  • Designing database queries, transactions, or connection management
  • Debugging slow queries, pool exhaustion, or deadlock issues
  • Implementing idempotency, optimistic locking, or event publishing with DB
  • Configuring read replicas, connection pools, or DB observability
  • Production readiness reviews of database usage in Go services
  • NOT: Migration file authoring (use golang-db-migration-conventions)
  • NOT: REST API design (use golang-api-conventions)
  • NOT: General Go language patterns (use go/1.26)

Prerequisites

  • Solid understanding of SQL and relational data modeling
  • Experience with Go database/sql package
  • Familiarity with transaction isolation concepts
  • Basic knowledge of connection pooling and HTTP request lifecycles

Philosophy

Driver-Agnostic by Default

All patterns use database/sql with portable SQL. Dialect-specific optimizations (e.g., CREATE INDEX CONCURRENTLY) are noted as optional enhancements, not defaults.

Application-Layer Focus

This skill covers runtime database usage in Go services. Schema evolution and migration tooling are covered by the companion golang-db-migration-conventions skill.

Safety-First Operations

Every pattern prioritizes data integrity, predictable failure modes, and production operability over convenience shortcuts.

Quick Reference Index

Connection & Safety

Core Operations

Integrity & Reliability

Operations & Scale

Essential Patterns Quick Reference

Connection Pool Setup

db, err := sql.Open("driver", dsn)
if err != nil {
    return fmt.Errorf("open database: %w", err)
}

// Tune pool — never use defaults blindly in production
db.SetMaxOpenConns(25)                  // limit concurrent connections
db.SetMaxIdleConns(10)                  // keep warm connections ready
db.SetConnMaxLifetime(30 * time.Minute) // recycle before server-side timeout
db.SetConnMaxIdleTime(5 * time.Minute)  // close idle connections

// Verify connectivity at startup
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := db.PingContext(ctx); err != nil {
    return fmt.Errorf("ping database: %w", err)
}

Parameterized Query

// Always use placeholders — never concatenate user input
const q = `SELECT id, email, name FROM users WHERE email = ?`
row := db.QueryRowContext(ctx, q, email)

Context-Scoped Query

func (r *UserRepo) GetByID(ctx context.Context, id int64) (*User, error) {
    ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
    defer cancel()

    const q = `SELECT id, email, name FROM users WHERE id = ?`
    var u User
    err := r.db.QueryRowContext(ctx, q, id).Scan(&u.ID, &u.Email, &u.Name)
    if errors.Is(err, sql.ErrNoRows) {
        return nil, ErrUserNotFound
    }
    return &u, err
}

Transaction with Rollback

func (r *OrderRepo) CreateWithItems(ctx context.Context, order Order, items []Item) error {
    tx, err := r.db.BeginTx(ctx, nil)
    if err != nil {
        return fmt.Errorf("begin tx: %w", err)
    }
    defer tx.Rollback() // no-op after Commit

    if err := r.insertOrder(ctx, tx, order); err != nil {
        return err
    }
    if err := r.insertItems(ctx, tx, items); err != nil {
        return err
    }
    return tx.Commit()
}

N+1 Prevention (Batch Load)

// Bad: query per user in loop
// Good: single query with IN clause
func (r *OrderRepo) OrdersByUserIDs(ctx context.Context, userIDs []int64) (map[int64][]Order, error) {
    if len(userIDs) == 0 {
        return nil, nil
    }
    placeholders := strings.Repeat("?,", len(userIDs)-1) + "?"
    q := fmt.Sprintf(`SELECT id, user_id, total FROM orders WHERE user_id IN (%s)`, placeholders)
    args := make([]any, len(userIDs))
    for i, id := range userIDs {
        args[i] = id
    }
    // ... scan and group by user_id
    return nil, nil
}

Transactional Outbox (Sketch)

// Within same transaction: write business data + outbox event
func (s *Service) PlaceOrder(ctx context.Context, order Order) error {
    tx, err := s.db.BeginTx(ctx, nil)
    if err != nil {
        return err
    }
    defer tx.Rollback()

    if err := s.insertOrder(ctx, tx, order); err != nil {
        return err
    }
    if err := s.insertOutboxEvent(ctx, tx, "order.placed", order.ID); err != nil {
        return err
    }
    return tx.Commit()
}

Navigation Guide

By Development Phase

Setup & Foundation:

  1. Connection Lifecycle - Pool configuration and startup validation
  2. Query Safety - Secure query patterns from day one
  3. Context & Timeouts - Request-scoped deadline propagation

Development:

  1. Transactions - Correct transaction boundaries
  2. Query Performance - Efficient data access patterns
  3. Schema Design - Constraint-based modeling

Production:

  1. Observability - Metrics, logging, tracing
  2. Reliability Engineering - Failure handling
  3. Security - Credential and access management

By Problem Domain

Slow Endpoints: Query Performance → Observability → Advanced Patterns

Data Races / Duplicates: Data Integrity → Transactions → Schema Design

Pool Exhaustion: Connection Lifecycle → Reliability Engineering → Observability

Multi-Region / Scale: Replication & Scaling → Advanced Patterns

Rule Severity Levels

Following RFC 2119 conventions:

  • MUST: Absolute requirement — violations risk data loss, security breach, or outage
  • SHOULD: Strong recommendation — violations need documented justification
  • MAY: Optional guidance — apply based on context and scale

Integration with Other Skills

Quick Decision Trees

Connection Pool Sizing

Known concurrent request load? → max_open = (expected_concurrent * queries_per_request) + headroom
Unknown load? → Start conservative (10-25), measure pool wait metrics, tune up
Long-running queries? → Lower max_open, enforce query timeouts first

Pagination Strategy

Small dataset (<10k rows)? → OFFSET acceptable for admin tools
Large dataset or user-facing? → Keyset/cursor pagination
Need total count? → Separate COUNT query or approximate counts

Retry Eligibility

Deadlock / serialization failure? → Retry with exponential backoff
Connection reset / timeout? → Retry (bounded)
Unique constraint violation? → Do NOT retry — handle as conflict
Business logic error? → Do NOT retry

Read Replica Routing

Read-after-write required? → Route to primary
Eventually consistent OK? → Route to replica
Replica lag exceeds SLO? → Fall back to primary or reject read

Senior Backend DB Checklist

Evidence expected in production services:

  1. Connection pool tuning with documented rationale
  2. Request-scoped timeouts and cancellation on every query
  3. Parameterized queries only — no string concatenation of user input
  4. Transaction correctness with explicit rollback and deadlock retry
  5. Query plan analysis and indexing strategy for hot paths
  6. Constraint-based data integrity (unique, foreign key, check)
  7. Idempotency support for write endpoints
  8. Read/write separation with replica lag awareness
  9. Slow query monitoring and pool saturation alerts
  10. Migration safety practices (see migration skill)
  11. Outbox pattern for reliable event publishing
  12. Capacity planning with growth projections
  13. Backpressure and circuit breakers around DB calls
  14. Disaster recovery and backup validation
  15. Workload isolation between OLTP, analytics, and batch jobs

Getting Started Recommendations

New Service: Connection Lifecycle → Query Safety → Context & Timeouts

Performance Issues: Query Performance → Observability → Advanced Patterns

Data Correctness: Data Integrity → Transactions → Schema Design

Production Hardening: Reliability Engineering → Security → Replication & Scaling

This skill provides enterprise-grade database operation patterns for Go developers building production systems. Each module contains detailed guidance, examples, and actionable patterns.

Files included

  • advanced-patterns.md
  • connection-lifecycle.md
  • context-timeouts.md
  • data-integrity.md
  • observability.md
  • query-performance.md
  • query-safety.md
  • reliability-engineering.md
  • replication-scaling.md
  • schema-design.md
  • security.md
  • SKILL.md
  • transactions.md

More skills