PeaLang Code Library

Database Performance

Index shape, query governance, locks, pooling and replication-aware routing.

1. Left-most prefix index eligibility

Use case. A query filtering on (tenant_id, status, created_at) can skip an index or scan millions of rows if the leading column is missing. Decide from predicates, not from table size.

# predicates are columns from WHERE clause.
const INDEX_PREFIX = ["tenant_id", "status", "created_at"]

function index_eligible(predicates) {
    if not (predicates[0] == "tenant_id") {
        return {"eligible": false, "reason": "NO_TENANT_PREFIX"}
    }
    return {"eligible": true, "reason": "USES_PREFIX"}
}

print "INDEX={index_eligible(["tenant_id", "status"]).eligible}"

Save as database-performance_01.pea; check pea fmt --check database-performance_01.pea && pea check database-performance_01.pea; run pea run database-performance_01.pea.

2. Query plan cost gate in CI migration

Use case. A new query is fast in dev with 20 rows and catastrophic in production with 40M. CI can compare estimated cost and reject queries predicted to exceed budget before merge.

# cost_units from EXPLAIN output normalized by host.
const MAX_COST = 10000

function plan_ok(estimated_cost, rows_examined, is_scan) {
    if is_scan and rows_examined > 1000000 {
        return {"ok": false, "reason": "FULL_SCAN"}
    }
    if estimated_cost > MAX_COST {
        return {"ok": false, "reason": "HIGH_PLAN_COST"}
    }
    return {"ok": true, "reason": "WITHIN_BUDGET"}
}

print "PLAN={plan_ok(12000, 2000000, true).ok}"

Save as database-performance_02.pea; check pea fmt --check database-performance_02.pea && pea check database-performance_02.pea; run pea run database-performance_02.pea.

3. Connection pool saturation guard

Use case. Requests timeout because every connection is held in long transactions. Reject new work when active connections exceed capacity minus reserve, rather than queuing indefinitely.

# active and capacity come from pool metrics.
const RESERVE = 4

function pool_accept(active, capacity) {
    let limit = capacity - RESERVE
    if active >= limit {
        return {"accept": false, "reason": "POOL_SATURATED"}
    }
    return {"accept": true, "reason": "OK", "available": limit - active}
}

print "POOL={pool_accept(96, 100).accept}"

Save as database-performance_03.pea; check pea fmt --check database-performance_03.pea && pea check database-performance_03.pea; run pea run database-performance_03.pea.

4. Long transaction detection and abort

Use case. An interactive transaction holds row locks for two minutes while a user types. The database cannot know intent; the application must abort or escalate before lock hold exceeds budget.

# age_ms from transaction wrapper.
const MAX_AGE_MS = 1500
const WARN_MS = 800

function txn_action(age_ms, in_retry) {
    if age_ms > MAX_AGE_MS {
        return {"action": "ABORT", "reason": "LOCK_HELD_TOO_LONG"}
    }
    if age_ms > WARN_MS {
        return {"action": "WARN", "reason": "LOCK_HELD"}
    }
    return {"action": "PROCEED", "reason": "WITHIN_BUDGET"}
}

print "TXN={txn_action(2000, false).action}"

Save as database-performance_04.pea; check pea fmt --check database-performance_04.pea && pea check database-performance_04.pea; run pea run database-performance_04.pea.

5. Lock wait timeout for admin DDL

Use case. An index build on a hot table waits for locks held by open transactions. Fail fast instead of blocking writes for minutes; schedule migration against maintenance window or replicas.

# waited_ms from DDL command.
function ddl_gate(waited_ms, lock_queue_depth) {
    if waited_ms > 2000 {
        return {"action": "ABORT_DDL", "reason": "LOCK_WAIT"}
    }
    if lock_queue_depth > 3 {
        return {"action": "RETRY_LATER", "reason": "LOCK_QUEUE"}
    }
    return {"action": "PROCEED_DDL", "reason": "CLEAR"}
}

print "DDL={ddl_gate(3000, 0).action}"

Save as database-performance_05.pea; check pea fmt --check database-performance_05.pea && pea check database-performance_05.pea; run pea run database-performance_05.pea.

6. Replication lag read-routing decision

Use case. Stale replica reads can show users old account state. Route writes and strong reads to primary only when replica lag is beyond threshold.

# lag_ms sampled per replica.
const MAX_LAG_MS = 250

function route_read(replica_lag_ms) {
    if replica_lag_ms > MAX_LAG_MS {
        return {"target": "PRIMARY", "reason": "STALE_REPLICA"}
    }
    return {"target": "REPLICA", "reason": "FRESH_ENOUGH"}
}

print "READ={route_read(400).target}"

Save as database-performance_06.pea; check pea fmt --check database-performance_06.pea && pea check database-performance_06.pea; run pea run database-performance_06.pea.

7. Deadlock retry policy for order updates

Use case. Concurrent updates to order rows hit deadlocks under load. Retry only idempotent, single-purpose updates with limited attempts; ledger writes outside lock are forbidden.

# error_code from DB driver; operation is idempotent by design.
function deadlock_retry(error_code, attempts) {
    if error_code == "DEADLOCK" and attempts < 3 {
        return {"retry": true, "delay_ms": 100 * attempts, "reason": "DEADLOCK"}
    }
    return {"retry": false, "delay_ms": 0, "reason": "NOT_RETRYABLE"}
}

print "DEADLOCK={deadlock_retry("DEADLOCK", 2).retry}"

Save as database-performance_07.pea; check pea fmt --check database-performance_07.pea && pea check database-performance_07.pea; run pea run database-performance_07.pea.

8. Shard key cardinality pre-flight

Use case. A low-cardinality shard key concentrates traffic on a few nodes. Reject the shard key before migration if distinct-values ratio predicts hotspot.

# distinct and total rows measured by sampling.
const MIN_DISTINCT_RATIO = 0.8
const MIN_TOTAL_ROWS = 100000

function shard_ok(distinct_values, total_rows) {
    if total_rows < MIN_TOTAL_ROWS {
        return {"ok": false, "reason": "TOO_FEW_ROWS"}
    }
    let ratio = distinct_values / total_rows
    if ratio < MIN_DISTINCT_RATIO {
        return {"ok": false, "reason": "LOW_CARDINALITY"}
    }
    return {"ok": true, "reason": "GOOD_DISTRIBUTION", "ratio": ratio}
}

print "SHARD={shard_ok(80000, 100000).ok}"

Save as database-performance_08.pea; check pea fmt --check database-performance_08.pea && pea check database-performance_08.pea; run pea run database-performance_08.pea.

9. Query timeout and context cancellation

Use case. A reporting query can block a shared connection while the user already closed the browser. Enforce wall-clock limit in the application so cancellation propagates.

# started_at and now in ms; budget_ms configured per query class.
const BUDGET_MS = 2000

function should_cancel(started_at, now, budget_ms) {
    if now - started_at > BUDGET_MS {
        return {"action": "CANCEL", "reason": "TIMEOUT"}
    }
    return {"action": "CONTINUE", "reason": "WITHIN_BUDGET"}
}

print "QUERY={should_cancel(1000, 5000, 2000).action}"

Save as database-performance_09.pea; check pea fmt --check database-performance_09.pea && pea check database-performance_09.pea; run pea run database-performance_09.pea.

10. Index rebuild vs drop decision

Use case. Indexes accumulate dead tuples after mass updates. Decide rebuild when bloat estimate exceeds threshold instead of paying full write cost always.

# bloat_ratio estimated by pages; index_size_mb gating.
const BLOAT_TRIGGER = 0.3

function index_action(bloat_ratio, size_mb) {
    if bloat_ratio > BLOAT_TRIGGER and size_mb > 50 {
        return {"action": "REBUILD", "reason": "BLOATED"}
    }
    return {"action": "MONITOR", "reason": "HEALTHY"}
}

print "INDEX={index_action(0.42, 120).action}"

Save as database-performance_10.pea; check pea fmt --check database-performance_10.pea && pea check database-performance_10.pea; run pea run database-performance_10.pea.

← Back to the Code Library