go
23 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package store
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgxpool"
)
func OpenPool(ctx context.Context, dsn string) (*pgxpool.Pool, error) {
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
return nil, err
}
cfg.MaxConns = 25
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.AfterConnect = func(ctx context.Context, conn *pgxpool.Conn) error {
_, err := conn.Exec(ctx, "SET statement_timeout = '2s'")
return err
}
return pgxpool.NewWithConfig(ctx, cfg)
}
1 file · go
Explain with highlit
Postgres stability depends on respecting its limits. I configure pgxpool with explicit MaxConns and MaxConnLifetime so the service doesn't accidentally open too many connections during bursts. I also set a session statement_timeout in AfterConnect, which is a pragmatic safety net when a query goes bad: the database will cancel it instead of letting it run for minutes and pin a connection. This is not a substitute for indexes and query tuning, but it prevents one slow query from turning into a cascading failure. I like returning a small wrapper that includes a Ping method used by readiness checks and graceful shutdown hooks.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
ruby
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
rails
performance
streaming
by codesnips
3 tabs
ruby
# BAD: N+1 query problem
@users = User.all
@users.each do |user|
puts user.posts.count # Fires query for each user!
end
ActiveRecord query optimization and N+1 prevention
ruby
rails
activerecord
by Sarah Mitchell
3 tabs
ruby
class AddSettingsToAccounts < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
add_column :accounts, :settings, :jsonb, null: false, default: {}
Postgres JSONB Partial Index for Feature Flags
rails
postgres
jsonb
by codesnips
3 tabs
go
package files
import (
"context"
"time"
Presigned S3 upload URLs (AWS SDK v2)
go
aws
s3
by Leah Thompson
1 tab
Share this code
Here's the card — post it anywhere.