package store
import (
"context"
"github.com/jackc/pgx/v5"
)
func ConsumeToken(ctx context.Context, tx pgx.Tx, token string) error {
var used bool
if err := tx.QueryRow(ctx, `SELECT used FROM tokens WHERE token=$1 FOR UPDATE`, token).Scan(&used); err != nil {
return err
}
if used {
return nil
}
_, err := tx.Exec(ctx, `UPDATE tokens SET used=true WHERE token=$1`, token)
return err
}
Optimistic locking is great for most user edits, but sometimes you need strict serialization—like decrementing inventory or consuming a one-time token. In those cases I use SELECT ... FOR UPDATE inside a transaction. The lock is scoped to the transaction, which means your code must be disciplined about ctx deadlines so locks don’t hang forever. The other key is ordering: if you lock multiple rows, lock them in a consistent order to avoid deadlocks. This pattern also pairs well with idempotency keys: acquire the row lock, check whether the work was already done, then perform the write. When used carefully, it’s a reliable way to enforce invariants without building distributed locks. The database is very good at this; let it do the hard work.
Related snips
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
class SignupForm
include ActiveModel::Model
include ActiveModel::Attributes
attribute :account_name, :string
attribute :email, :string
Shallow Controller, Deep Params: Form Object Pattern
# 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
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
Share this code
Here's the card — post it anywhere.