Skip to content

henriqueatila/golang-gin-best-practices / skills/golang-gin-psql-dba

golang-gin-psql-dba

Flagged

PostgreSQL DBA for Go Gin APIs. Use when designing schemas, analyzing migrations, choosing indexes, optimizing queries, or selecting extensions (pgvector, PostGIS, TimescaleDB).

FileKindSize
SKILL.mdskill md9.9 KB
metadata.jsonconfig668 B
references/backup-and-recovery-managed-and-schedules.mdmarkdown4.3 KB
references/backup-and-recovery-strategies.mdmarkdown4.8 KB
references/backup-and-recovery-wal-and-validation.mdmarkdown2.7 KB
references/extensions-toolkit-crypto-and-uuid.mdmarkdown4.1 KB
references/extensions-toolkit-partman-and-trgm.mdmarkdown4.5 KB
references/extensions-toolkit-pgaudit-and-stats.mdmarkdown4.3 KB
references/extensions-toolkit-setup-and-cron.mdmarkdown3.8 KB
references/index-strategy-maintenance-and-explain.mdmarkdown4.4 KB
references/index-strategy-types-and-variants.mdmarkdown3.8 KB
references/migration-impact-backfill-and-lock-timeout.mdmarkdown3.5 KB
references/migration-impact-lock-timeout.mdmarkdown4.6 KB
references/migration-impact-locks-and-operations.mdmarkdown6.4 KB
references/paradedb-advanced-search-and-hybrid.mdmarkdown4.7 KB
references/paradedb-go-integration-and-tips.mdmarkdown4.9 KB
references/paradedb-setup-and-basic-search.mdmarkdown4.5 KB
references/pgvector-capacity-and-performance.mdmarkdown4.3 KB
references/pgvector-queries-and-go-integration.mdmarkdown4.4 KB
references/pgvector-setup-and-schema.mdmarkdown4.9 KB
references/postgis-go-integration-and-performance.mdmarkdown3.8 KB
references/postgis-setup-types-and-indexes.mdmarkdown4.3 KB
references/query-performance-pool-and-replicas.mdmarkdown4.6 KB
references/query-performance-stats-and-vacuum.mdmarkdown4.2 KB
references/replication-and-ha-clusters.mdmarkdown3.4 KB
references/replication-and-ha-go-readwrite.mdmarkdown4.0 KB
references/replication-and-ha-go-resilience.mdmarkdown4.8 KB
references/replication-and-ha-lag-monitoring.mdmarkdown3.3 KB
references/replication-and-ha-logical.mdmarkdown2.2 KB
references/replication-and-ha-managed-services.mdmarkdown2.0 KB
references/replication-and-ha-overview.mdmarkdown3.1 KB
references/replication-and-ha-streaming-setup.mdmarkdown3.6 KB
references/row-level-security-go-integration-and-pitfalls.mdmarkdown5.5 KB
references/row-level-security-setup-and-policies.mdmarkdown5.8 KB
references/schema-design-complete-example.mdmarkdown6.9 KB
references/schema-design-constraints-and-normalization.mdmarkdown4.2 KB
references/schema-design-naming-and-types.mdmarkdown3.9 KB
references/schema-design-soft-delete-and-tenancy.mdmarkdown5.1 KB
references/timescaledb-aggregates-compression-retention.mdmarkdown5.7 KB
references/timescaledb-go-integration.mdmarkdown3.5 KB
references/timescaledb-setup-and-hypertables.mdmarkdown4.8 KB

references/timescaledb-go-integration.md

View on GitHub
# TimescaleDB — Go Integration and Complete Example

## Batch Writer

Writing every request synchronously adds latency. Collect metrics in a buffered channel and flush in batches every few seconds.

```go
// internal/repository/metrics_writer.go
package repository

import (
    "context"
    "fmt"
    "log/slog"
    "time"

    "github.com/jmoiron/sqlx"
    "myapp/internal/domain"
)

const batchSize = 500

type MetricsBatchWriter struct {
    db     *sqlx.DB
    ch     chan domain.APIMetric
    logger *slog.Logger
}

func NewMetricsBatchWriter(db *sqlx.DB, logger *slog.Logger) *MetricsBatchWriter {
    return &MetricsBatchWriter{
        db:     db,
        ch:     make(chan domain.APIMetric, 10_000),
        logger: logger,
    }
}

// Enqueue is non-blocking; drops metric if buffer is full.
func (w *MetricsBatchWriter) Enqueue(m domain.APIMetric) {
    select {
    case w.ch <- m:
    default:
        w.logger.Warn("metrics buffer full, dropping metric", slog.String("endpoint", m.Endpoint))
    }
}

// Run starts the flush loop. Call as a goroutine; cancel ctx to stop.
func (w *MetricsBatchWriter) Run(ctx context.Context) {
    ticker := time.NewTicker(5 * time.Second)
    defer ticker.Stop()
    batch := make([]domain.APIMetric, 0, batchSize)

    flush := func() {
        if len(batch) == 0 {
            return
        }
        if err := w.insertBatch(ctx, batch); err != nil {
            w.logger.Error("metrics flush failed", slog.Any("error", err))
        }
        batch = batch[:0]
    }

    for {
        select {
        case m := <-w.ch:
            batch = append(batch, m)
            if len(batch) >= batchSize {
                flush()
            }
        case <-ticker.C:
            flush()
        case <-ctx.Done():
            for len(w.ch) > 0 {
                batch = append(batch, <-w.ch)
            }
            flush()
            return
        }
    }
}

func (w *MetricsBatchWriter) insertBatch(ctx context.Context, batch []domain.APIMetric) error {
    const q = `INSERT INTO api_metrics (time, endpoint, method, status, duration_ms, user_id, ip)
               VALUES (:time, :endpoint, :method, :status, :duration_ms, :user_id, :ip)`
    _, err := w.db.NamedExecContext(ctx, q, batch)
    if err != nil {
        return fmt.Errorf("insertBatch: %w", err)
    }
    return nil
}
```

## Gin Middleware and Wiring

```go
// Middleware: record start time, call c.Next(), enqueue APIMetric{Time, Endpoint: c.FullPath(),
// Method, Status: c.Writer.Status(), DurationMs, UserID: c.GetString("user_id"), IP: c.ClientIP()}

// main.go wiring:
metricsWriter := repository.NewMetricsBatchWriter(db, logger)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go metricsWriter.Run(ctx)
r.Use(middleware.MetricsRecorder(metricsWriter))
```

## Dashboard Queries

```sql
-- Top 10 slowest endpoints (last 24 hours)
SELECT endpoint, method,
       ROUND(AVG(avg_ms)::numeric, 2) AS avg_ms,
       SUM(requests) AS total_requests
FROM api_metrics_hourly
WHERE bucket >= now() - INTERVAL '24 hours'
GROUP BY endpoint, method ORDER BY avg_ms DESC LIMIT 10;

-- Error rate by endpoint (last 7 days)
SELECT endpoint,
       SUM(requests) AS total,
       ROUND(100.0 * SUM(errors) / NULLIF(SUM(requests), 0), 2) AS error_pct
FROM api_metrics_hourly
WHERE bucket >= now() - INTERVAL '7 days'
GROUP BY endpoint HAVING SUM(requests) > 100
ORDER BY error_pct DESC;
```

> For complete DDL (hypertable + compression + retention + continuous aggregate): see [timescaledb-aggregates-compression-retention.md](timescaledb-aggregates-compression-retention.md).
deprecation-and-migrationaddyosmani/agent-skillsManages deprecation and migration. Use when removing old systems, APIs, or features. Use when migrating users from one implementation to another. Use when migrating a database schema in production, such as renaming or dropping a column without downtime (expand/contract). Use when deciding whether to maintain or sunset existing code.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
performance-optimizationaddyosmani/agent-skillsOptimizes application performance across frontend, backend, queries, and databases. Use when performance requirements exist, when you suspect performance regressions, when Core Web Vitals or load times need improvement, when N+1 query patterns need fixing, or when profiling reveals bottlenecks.Stars: 119kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall
agent-cost-reportthedotmack/claude-memBelievable agent cost report for any period, default the last 7 full days PT, not counting today. Measured tokens from Claude Code transcripts priced at OpenRouter list prices (ESTIMATED), measured provider spend when a sanctioned source exists, note-taker cost separate, Timing-style HTML/PDF plus report.json, line-items.csv, evidence.json.Stars: 118kUpdated Claude CodeCodexVerifiedInstall