Skip to main content

Staff / Database Architecture — STQ001–STQ080

IDQuestionExpected answerReasoningCommon wrong answerFollow-upRelated chapter
STQ001How do you decide one shared database vs multiple databases/services?Evaluate domain ownership, transaction boundaries, coupling, blast radius, compliance, scaling, restore needs, team autonomy and fleet cost.Splitting removes local joins/transactions but can improve ownership/isolation.“Microservices require one DB each.”What data should remain together?191 — Staff Architecture
STQ002What does data ownership mean at organization scale?One accountable domain/team controls schema writes/contracts/evolution; other domains consume APIs/events/read contracts rather than mutating tables opportunistically.Ownership reduces hidden coupling and migration conflicts.“Whoever has DB credentials can write.”How migrate shared-table ownership?191 — Staff Architecture
STQ003How do you define database platform tiers?Standardize SLO/RPO/RTO, HA, backup/PITR, capacity, security, support, version, extension and cost profiles by workload criticality.Not every database needs identical cost/reliability.“One golden configuration for all workloads.”Example bronze/silver/gold differences?191 — Staff Architecture
STQ004How do you set an RPO/RTO policy?Start from business impact and legal obligations, then choose technical controls capable of meeting tested objectives and budget.Technology follows recovery requirement.“Copy provider defaults.”How prove the objective?86,189 — DR/Reliability
STQ005How do you build a restore-testing program?Automated periodic restores plus scenario drills, integrity/app verification, measured duration, failure injection, ownership and remediation tracking.Recovery evidence must stay current as schema/data grow.“Annual manual restore is enough.”How detect backup format drift?86 — Restore/DR
STQ006What is a credible multi-region PostgreSQL strategy?Define write ownership/consistency, latency, replication mode, failure detection/promotion/fencing, routing, data residency, RPO/RTO, rejoin and operator authority.“Multi-region” is not just adding replicas.“Active-active everywhere.”When accept single write region?90,191
STQ007Why is active-active relational writing hard?Concurrent writers need conflict resolution/consensus/global constraints/ordering; network partitions force consistency-vs-availability decisions.Local PK/FK/transactions do not automatically become global.“Logical replication makes both primaries.”Which domains tolerate conflicts?141–143
STQ008How does CAP apply to PostgreSQL HA?During network partition, a safe single-primary system generally sacrifices availability on one side to preserve one writable history; fencing/consensus decide authority.Partition tolerance is an operating reality.“PostgreSQL is CP or AP at all times.”What does synchronous replication change?142 — CAP
STQ009How do you choose synchronous replication topology?Based on RPO, region/AZ latency, failure correlation, quorum availability and commit SLO; define which acknowledgement stage and fallback policy.Quorum design affects both durability and availability.“Two sync replicas means zero data loss in every failure.”What if all sync standbys disappear?90 — HA
STQ010How do you prevent split brain operationally?Single promotion authority/consensus, fencing old primary, controlled routing, epoch/timeline awareness, tested failover/rejoin procedures.Replication alone does not revoke old leader.“DNS points clients to the new one, so safe.”How verify fencing in drill?90 — HA
STQ011What is your database version support policy?Approved major/minor windows, current security minors, upgrade lead time before EOL, extension/driver compatibility matrix, rehearsal and exception process.Version risk is governance, not ad hoc ops.“Upgrade only when provider forces us.”How handle PG14 EOL?169 — Versioning
STQ012How do you govern PostgreSQL extensions?Approved catalog, owner/security review, versions, native-code trust, provider availability, backup/restore, upgrade testing, observability and exception process.Extensions affect platform portability and lifecycle.“Developers can install any extension in app migrations.”How treat pgvector?183 — Extension Ecosystem
STQ013How do you decide managed vs self-managed PostgreSQL?Compare control, staff expertise, compliance, HA/backup obligations, extensions, cost, performance, upgrade cadence and operational toil.Managed shifts responsibility; it does not remove it.“Managed means no DBA/database engineering needed.”Which responsibilities remain with app team?139 — Cloud PostgreSQL
STQ014How do you evaluate serverless PostgreSQL?Workload burstiness, cold/warm behavior, connection/proxy model, transaction/session semantics, autoscaling lag, cost, limits, HA/recovery and portability.Elastic compute changes operational constraints but not SQL semantics.“Serverless has infinite connections.”How handle functions-as-a-service?140 — Serverless PostgreSQL
STQ015What metrics belong in an organization-wide PostgreSQL SLO dashboard?Availability, query/request latency, pool waits, errors, locks, transaction age, vacuum/XID, WAL/archive/slots, replication lag, CPU/memory/I/O/disk, backup/restore freshness and capacity.SLOs need user impact plus leading reliability indicators.“CPU, RAM and disk only.”Which metrics are symptoms vs causes?108 — Monitoring
STQ016How do you standardize query observability across services?Require application_name/correlation, traces with safe fingerprints, pg_stat_statements, latency/call/row/I/O/WAL metrics, logs with privacy policy, shared dashboards/runbooks.Cross-layer correlation reduces time-to-diagnosis.“Enable log_statement=all globally.”How map queryid to endpoint?105,133
STQ017How do you set organization-wide migration guardrails?Expand/contract by default, lock/statement timeouts, concurrent index rules, NOT VALID validation, batch backfill framework, peer review, production-size rehearsal, rollback/forward-fix and CI checks.Migrations are production code with unique failure modes.“ORM migrations are automatically safe.”Which DDL should require manual review?125–128
STQ018What should a schema-review checklist include?Facts/invariants, candidate keys, null/temporal semantics, FKs/actions, normalization, query access, indexes, transaction/concurrency, tenancy/security, migration/evolution, retention/recovery.Schema decisions persist longer than feature code.“Only naming and types.”How enforce review automatically?190–191
STQ019How do you govern query/index changes?Require workload evidence, EXPLAIN before/after, frequency/latency, index size/write cost, production data distribution, rollback and post-deploy monitoring.Prevents local read wins that hurt system writes.“Any missing-index recommendation can auto-deploy.”How use hypothetical indexes?188 — Performance Architecture
STQ020How do you define capacity headroom?Reserve CPU/I/O/memory/connection/disk/WAL space for spikes, failover, maintenance, index builds/backfills and growth lead time; quantify by workload tier.Running near 100% makes recovery and maintenance fail.“20% free disk is enough universal rule.”What temporary space can index build need?162 — Capacity Planning
STQ021When is vertical scaling the right answer?When one-node semantics still fit and bottleneck is resource capacity with acceptable cost/downtime; simpler than premature distribution.Complexity cost matters.“Vertical scaling is not scalable architecture.”When does it stop helping?163–164
STQ022When do read replicas become architecture, not just capacity?Once routing/staleness/read-your-write/failover/load balancing are product semantics and operational dependencies.Replicas change consistency model visible to users.“They are transparent copies.”How document staleness budget?143,163
STQ023When do you recommend caching?For measured repeated expensive/stable reads after understanding DB cost, with explicit invalidation/staleness/tenant/failure strategy.Cache adds another consistency state.“Cache every SELECT.”Cache-aside stampede control?144 — Caching
STQ024How do you decide materialized view vs cache?MV is DB-managed relational snapshot good for SQL/reporting with refresh semantics; cache is application/key-oriented with independent lifecycle/eviction.Freshness, query shape and ownership differ.“They are interchangeable.”REFRESH CONCURRENTLY requirement?40 — Materialized Views
STQ025How do you decide partitioning policy across a fleet?Standardize only for proven lifecycle/pruning/maintenance patterns; choose key/granularity/retention/partition automation/index/uniqueness rules and cap partition counts.Partitioning is operational architecture.“Partition all tables by month.”What if tenant and time both matter?115 — Partitioning
STQ026How do you decide sharding trigger points?Explicit single-primary write/size/residency/blast-radius/latency limits after local optimization; quantify expected benefit and distributed cost.“Large table” alone is insufficient.“Shard at 1 TB.”What pre-shard measurements?116,191
STQ027What organizational capabilities are required before sharding?Routing ownership, rebalancing tooling, shard-aware migrations/observability/backups/failover, global-ID/uniqueness policy, cross-shard query/transaction strategy and on-call expertise.Sharding multiplies operational fleet complexity.“ORM will hide shards.”How test rebalancing?116 — Sharding
STQ028How do you isolate a noisy tenant?Measure resource source; optimize query/index/quotas, workload scheduling, partition/cache; optionally move tenant to isolated DB/shard tier with migration/routing plan.Isolation can be incremental.“Immediately database-per-tenant for everyone.”What identifies tenant hotness?49,191
STQ029How do you design a hybrid tenant architecture?Default shared schema for small tenants, extract large/regulatory tenants to dedicated DBs behind a routing/ownership abstraction; keep schema/migration compatibility.Balances efficiency and isolation.“Hybrid means duplicate application code.”How move tenant online?49,191
STQ030How do you support data residency?Map tenant/data classes to allowed regions, enforce routing/storage/backup/replica/log residency, migrations and operator access; document cross-region metadata exceptions.Residency includes copies, not just primary.“Put primary in-country.”What about PITR archives?187,191
STQ031How do you classify database data for security?Public/internal/confidential/restricted/PII/payment etc., then derive role/network/encryption/logging/retention/audit/backup controls.Security controls should follow data risk.“All database data is equally sensitive.”How does classification affect logs?187 — Security Architecture
STQ032How do you design database roles at fleet scale?Separate owner/migration/runtime/read-only/monitoring/admin/break-glass identities, group memberships, defaults, short-lived auth/secret rotation, no runtime ownership.Privilege boundaries limit blast radius.“One service superuser simplifies ops.”How audit grants?92–94
STQ033What is a break-glass database access model?Strongly restricted emergency admin role with approval/MFA/short-lived credentials/audit, not normal service use.Preserves emergency capability without persistent broad privilege.“Everyone on-call gets superuser password.”How test without normalizing access?187 — Security Architecture
STQ034How do you handle database secrets?Prefer managed/short-lived identity where possible; scoped roles, secret manager, rotation, no source/log exposure, TLS verification, revoke on incident.Credential lifecycle is part of DB security.“Environment variable is enough forever.”OAuth in PG18?94 — Authentication
STQ035How do you govern RLS use?Define when required, approved tenant-context mechanism, non-owner runtime roles, policy templates, negative tests, performance review, security-definer rules and emergency/admin path.RLS can be powerful but subtle.“Enable RLS and every table is safe.”How handle background jobs?96 — RLS
STQ036What security risks exist in search_path across a platform?Object shadowing in writable schemas, especially elevated functions/migrations/extensions; restrict CREATE, qualify names, set safe paths.Namespace control is privilege control.“Only naming conflict inconvenience.”Which schemas are trusted?07 — Search Path
STQ037How do you review third-party DB migrations/extensions for supply-chain risk?Pin sources/versions, verify provenance/signatures/builds, inspect privilege/native-code requirements, test offline, control install role and rollout, inventory dependencies.DB native extensions can execute highly privileged code.“Open-source extension is safe by definition.”Managed-service allowlist benefit?104,183
STQ038How do you design PII deletion with backups?Delete/anonymize active systems, define backup retention/expiry and restore re-deletion workflow, legal holds, audit proof and derivative copies.Immutable backups complicate immediate erasure.“Delete row from primary and requirement is complete.”What about replicas/logs?187 — Security Architecture
STQ039How do you design a database incident command model?Clear incident commander, DB/operator/app roles, severity/escalation, safe-change authority, evidence timeline, stakeholder comms, recovery validation and postmortem.Coordination prevents conflicting emergency actions.“Whoever sees it first changes settings.”What is break-glass change policy?160 — Incident Debugging
STQ040Which failure drills should a PostgreSQL platform run?Restore/PITR, primary loss/failover/fencing, replica lag, disk pressure, archive failure, slot retention, connection storm, long transaction, migration lock, autovacuum/XID and credential rotation.Reliability improves through practiced failure.“Only backup restore.”How score drill readiness?159,189
STQ041How do you define safe failover automation?Conservative health signals, quorum/authority, fencing, RPO-aware candidate selection, routing, app retry, validation and human override/observability.Fast incorrect promotion is worse than brief outage.“Promote after one failed ping.”False-positive partition scenario?90 — HA
STQ042How do you choose backup retention tiers?Match RPO/history/compliance, data-change risk, restore cost and storage budget; combine recent high-frequency PITR with longer logical/physical archives where needed.Retention is business/recovery policy.“Keep everything forever.”How test old backup compatibility?85–87
STQ043How do you architect recovery from logical corruption?Independent backups/PITR, detect earliest bad change, restore to isolated timeline, verify, extract/cut over/replay safe changes, preserve evidence.HA replicas likely contain same logical mistake.“Fail over to replica.”How minimize lost good writes after bad event?87,189
STQ044How do you design a migration platform?Versioned migrations, ownership, advisory/CI coordination, timeouts, online DDL primitives, batch backfill service, schema compatibility windows, metrics, pause/resume and audit.Repeated migration safety can be productized.“Each service writes arbitrary SQL on startup.”How handle multiple instances racing migrations?125–128
STQ045How do you prevent schema drift?Declarative/version-controlled migrations, environment diff/audit, restricted DDL roles, CI, periodic catalog comparison and managed exceptions.Direct production DDL creates invisible divergence.“ORM schema sync in prod.”How reconcile emergency change?125 — Migrations
STQ046What is the role of backward compatibility in schema evolution?Rolling code versions must coexist; additive changes first, delayed removal, compatible defaults/null semantics, dual-read/write only with reconciliation.Deployment and DB change timelines differ.“Database and app deploy atomically.”How long keep compatibility?126 — Zero-Downtime Migrations
STQ047How do you manage backfills organization-wide?Standard worker with keyset batching, idempotency, checkpoints, throttles, rate limits, observability, pause/resume, tenant fairness and completion validation.Avoid bespoke one-off massive UPDATEs.“Run SQL script from laptop.”How prevent replica overload?128 — Backfills
STQ048What should a data migration acceptance gate require?Correctness reconciliation, zero/known unmatched rows, lock/latency/WAL/lag budgets, resumability, rollback/forward-fix, constraint validation and post-deploy monitoring.“Rows updated successfully” is insufficient.“Exit code 0.”How reconcile counts/hashes?128 — Backfills
STQ049How do you establish SQL standards without blocking teams?Small mandatory correctness/security rules plus linters/templates/review examples, performance evidence for hot paths, training/handbook and exceptions for justified advanced SQL.Guardrails beat universal style dogma.“Ban raw SQL; ORMs only.”Which rules are mandatory?155,157
STQ050How do you govern ORM usage?SQL-first mental model, enforce DB constraints, transaction ownership patterns, query logging/fingerprints, N+1 detection, raw escape hatch and migration review.ORM is a productivity layer, not semantic authority.“ORM makes DB portable and safe automatically.”How detect generated bad SQL?123–124
STQ051How do you choose a database abstraction boundary?Align with domain ownership/use cases, explicit transaction context and query projections; avoid generic CRUD that hides SQL and cross-domain mutation.Data access design shapes consistency and evolvability.“One generic repository for every table.”When expose read model?152 — DB API Design
STQ052How do you define transaction boundaries across services?Keep atomic transaction inside one owning database/domain; cross-service workflows use idempotency/outbox/sagas/reconciliation, not long distributed DB locks by default.Network boundaries change failure model.“Open transactions in both services simultaneously.”When 2PC justified?153 — Transaction Boundaries
STQ053How do you reason about 2PC?It can provide atomic commit across participants but adds coordinator availability, prepared-transaction operational complexity and blocking; use only when requirements justify.Distributed atomicity has operational cost.“2PC solves all distributed consistency.”Alternative for payments/events?141,153
STQ054How do you govern idempotency across an API platform?Standard key scope/format, request hash, durable state/result, TTL/retention, concurrent behavior, external callback dedupe and observability.Retry semantics should be consistent across services.“Client-generated UUID alone is enough.”How handle same key/different body?151 — Idempotency
STQ055How do you govern outbox patterns?Shared schema/library or standard contract for event IDs, aggregate/order, claim/publish, retries, consumer idempotency, retention, metrics and replay.Prevents every team reimplementing failure semantics differently.“One global outbox table for all domains necessarily.”Per-domain vs shared publisher?150 — Outbox
STQ056How do you decide PostgreSQL queue vs broker at platform level?Classify workload by transactional locality, throughput, fan-out, retention/replay, routing, independent scaling and operational ownership; support both with guidance.Different systems solve different delivery semantics.“Standardize on one queue technology for everything.”Example DB-local job?145 — Queue Pattern
STQ057How do you design analytics extraction from OLTP?CDC/logical replication/outbox/ETL into analytics store, define schema contracts, backfill, ordering/idempotency, privacy and lag/freshness SLO; protect primary resources.Analytics is often eventually consistent.“Run all BI directly on primary.”When use logical replication?89,192
STQ058How do you architect AI/RAG data isolation?Typed tenant/document/permission metadata, RLS/authorization filtering, vector extension controlled, provenance/model versions, retention/deletion, async ingestion jobs and evaluation data.Similarity search must not bypass access control.“Vector index is separate from DB permissions.”Where filter permissions?185–186
STQ059How do you evaluate vector-search scalability in PostgreSQL?Dataset/dimension/recall/latency/filter selectivity/write rate, ANN index memory/storage/build cost, tenant isolation, extension version; benchmark against dedicated systems.Choose from evidence, not trend.“pgvector scales infinitely because PostgreSQL does.”When separate vector service?185 — pgvector
STQ060How do you plan extension major-version upgrades?Compatibility matrix, staging restore, extension upgrade path/order, dump/restore behavior, provider support, regression/performance tests and rollback.Core PG upgrade success does not guarantee extension compatibility.“Extensions automatically upgrade with PostgreSQL.”What if target provider lacks extension?104,169,183
STQ061How do you define database cost attribution?Attribute storage/index/WAL/backup, instance/compute, I/O, replicas, query/workload and tenant/service utilization; expose unit costs and growth.Cost informs architecture and optimization priorities.“Split instance bill equally among teams.”How quantify index cost?162,188
STQ062How do you decide when to delete old indexes fleet-wide?Evidence from usage/fingerprints, constraints, replicas/rare jobs, size/write cost and owner sign-off; staged removal/monitoring/rollback.Governance avoids both index sprawl and unsafe cleanup.“Auto-drop after 30 days zero scans.”What about failover replica workload?57,107
STQ063How do you manage planner configuration centrally?Keep defaults unless measured platform-specific evidence; changes require workload suite, version awareness, rollback and per-role/query scope where possible.Planner costs are global behavioral levers.“Set random_page_cost=1 on every SSD.”Which setting is not allocated memory?111–112
STQ064How do you handle per-workload memory classes?Role/session defaults for OLTP vs analytics/maintenance, bounded concurrency, temp-file limits/monitoring, parallelism awareness.One work_mem cannot suit every query class.“Set huge work_mem globally.”Why per-operation multiplication?112 — Memory Config
STQ065How do you protect maintenance capacity?Keep CPU/I/O/disk/connection headroom, schedule or throttle vacuum/index/backups, resource-class workloads, monitor age/lag; never starve correctness maintenance indefinitely.Maintenance is part of service capacity.“Use 100% capacity for customer traffic.”What happens to vacuum at peak forever?75–76,162
STQ066What is a safe autovacuum policy for fleet heterogeneity?Defaults plus per-table tuning based on size/change patterns, age alerts, long-transaction controls, observability and review of insert/update-heavy outliers.Percent thresholds affect huge/small tables differently.“One global scale factor fits all.”How automate candidate detection?114 — Autovacuum Config
STQ067How do you approach bloat fleet-wide?Prevention first; monitor growth/dead/HOT/vacuum/index churn, prioritize actual I/O/cost, choose VACUUM/REINDEX/repack/rewrite with downtime/space plans.Bloat remediation is workload-risk trade-off.“Nightly VACUUM FULL all tables.”How identify false positives?78 — Bloat
STQ068How do you set WAL/archive/slot storage guardrails?Rate/retention forecasts, free-space alerts, archive freshness, slot retained-byte limits/policy, max_wal_size understanding, emergency runbooks.WAL can exceed naive config expectations.“max_wal_size caps pg_wal absolutely.”Why can slot override it?113,137
STQ069How do you govern replication slots?Named owner/purpose, active-state/retained-WAL monitoring, retention caps, lifecycle deletion, consumer SLO/resync procedure and incident escalation.Forgotten slots are disk risks.“Slots clean themselves when consumers disappear.”Logical slot catalog horizon?137 — Slots
STQ070How do you design read-replica consistency contracts for product teams?Endpoint classes: strong/read-your-write→primary or LSN wait; stale-tolerant→replica with lag budget; expose fallback behavior and telemetry.Makes consistency an API contract.“Developers choose primary/replica ad hoc.”How test failover/staleness?143 — Consistency Models
STQ071How do you define a deprecation path for database objects?Usage inventory, owner/consumer notification, compatibility view/dual period, telemetry proving no use, delayed drop, recovery/restore considerations.Database consumers can be hidden/long-lived.“Search application repo and drop.”How handle BI queries?126,191
STQ072How do you design metadata/catalog tooling?Inventory databases/schemas/tables/owners/sizes/PK/FK/indexes/extensions/versions/PII/tier, links to service/on-call and drift/status.Platform decisions need discoverability.“pgAdmin is the catalog.”Which system catalogs feed it?106 — System Catalogs
STQ073How do you make database knowledge scalable across teams?Handbook, training/labs, office hours, reusable modules, migration/query review automation, incident writeups, scorecards and clear escalation paths.Architecture scales through systems and people.“Hire one DBA to approve everything.”Which topics should every backend engineer know?190–191
STQ074What should a staff-level database design review produce?Decision record with invariants/data model, workload/plan/index assumptions, consistency/concurrency, security, migrations, capacity, recovery/HA, monitoring, costs, alternatives and trigger points.Review should leave testable decisions, not preferences.“Approved architecture diagram.”What are trigger points?191–192
STQ075How do you define architectural trigger points?Measurable thresholds/conditions that justify next complexity step, e.g. p99/SLO, storage/WAL growth, write saturation, tenant size, residency, restore duration.Avoids premature scaling and crisis-driven decisions.“Migrate when it feels slow.”Example shard trigger?191 — Staff Architecture
STQ076How do you compare PostgreSQL with another database responsibly?Compare required semantics/workload/operations/ecosystem, run representative tests, identify migration/portability differences and team skills; avoid brand absolutes.Database choice is context-specific.“PostgreSQL always wins because features.”PostgreSQL vs document store case?181–182
STQ077What makes PostgreSQL a platform rather than just storage?Rich SQL/types/indexes/transactions, server programming, extensions, replication, security, observability and tooling enable many workload patterns under one operational model.Power requires governance to avoid coupling.“Use every feature in every service.”Where should boundaries remain?183,191
STQ078How do you avoid over-centralizing on PostgreSQL?Define fit criteria and escape hatches for analytics/search/streaming/vector/distributed workloads when requirements exceed PostgreSQL strengths; preserve ownership/contracts.A good platform can recommend another tool.“One database simplifies everything forever.”Example dedicated search trigger?181–188
STQ079How do you measure success of a database platform program?Fewer/severer incidents, restore/failover success, upgrade currency, migration failure rate, SLO attainment, capacity/cost efficiency, security findings, developer lead time and adoption of guardrails.Platform value is reliability + velocity, not number of standards.“Number of databases migrated.”Which leading indicators matter?161,191
STQ080What distinguishes staff-level database architecture?Organization-level ownership/governance, cross-system trade-offs, reliability/security/cost strategy, reusable platform mechanisms, explicit evolution triggers, and influence through evidence rather than local tuning alone.Staff scope shapes many teams and long-term system behavior.“Knowing PostgreSQL internals deeper than everyone.”Give one policy you would institutionalize first.191 — Staff Architecture