InterviewTreedInterviewTreed

InterviewTreed Question Bank

Databases & Caching Interview Questions and Answers

Prepare for database and caching interviews, covering relational and NoSQL databases, database architecture, indexing, transactions, Redis, distributed caching, performance optimization, and data consistency.

Total Questions

80

Beginner

24

Intermediate

39

Advanced

17

Beginner Questions

Foundational concepts, terminology, and core ideas.

Q1Relational database fundamentals

What is a relational database?

Interview answer for what is a relational database? with practical syntax and implementation patterns.

Answer

What is a relational database? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q2Relational database fundamentals

What are tables, rows, columns, and constraints?

Interview answer for what are tables, rows, columns, and constraints? with practical syntax and implementation patterns.

Answer

What are tables, rows, columns, and constraints? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q3Relational database fundamentals

What is a primary key?

Interview answer for what is a primary key? with practical syntax and implementation patterns.

Answer

What is a primary key? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q4Relational database fundamentals

What is a foreign key?

Interview answer for what is a foreign key? with practical syntax and implementation patterns.

Answer

What is a foreign key? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q5Relational database fundamentals

What is normalization?

Interview answer for what is normalization? with practical syntax and implementation patterns.

Answer

What is normalization? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q8Relational database fundamentals

What are ACID properties?

Interview answer for what are acid properties? with practical syntax and implementation patterns.

Answer

What are ACID properties? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q11SQL queries and transactions

What is the difference between WHERE and HAVING?

Interview answer for what is the difference between where and having? with practical syntax and implementation patterns.

Answer

What is the difference between WHERE and HAVING? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q12SQL queries and transactions

Explain INNER JOIN, LEFT JOIN, and FULL JOIN

Interview answer for explain inner join, left join, and full join with practical syntax and implementation patterns.

Answer

Explain INNER JOIN, LEFT JOIN, and FULL JOIN is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q13SQL queries and transactions

What is a subquery?

Interview answer for what is a subquery? with practical syntax and implementation patterns.

Answer

What is a subquery? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q21Indexing and query performance

What is a database index?

Interview answer for what is a database index? with practical syntax and implementation patterns.

Answer

What is a database index? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q28Indexing and query performance

What is a table scan and when is it acceptable?

Interview answer for what is a table scan and when is it acceptable? with practical syntax and implementation patterns.

Answer

What is a table scan and when is it acceptable? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q31Relational data modeling

One-to-one, one-to-many, and many-to-many relationships

Interview answer for one-to-one, one-to-many, and many-to-many relationships with practical syntax and implementation patterns.

Answer

One-to-one, one-to-many, and many-to-many relationships is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q32Relational data modeling

What is a junction table?

Interview answer for what is a junction table? with practical syntax and implementation patterns.

Answer

What is a junction table? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q33Relational data modeling

What are unique, check, and not-null constraints?

Interview answer for what are unique, check, and not-null constraints? with practical syntax and implementation patterns.

Answer

What are unique, check, and not-null constraints? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q41NoSQL database concepts

What is a NoSQL database?

Interview answer for what is a nosql database? with practical syntax and implementation patterns.

Answer

What is a NoSQL database? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q42NoSQL database concepts

SQL vs NoSQL: how do you choose?

Interview answer for sql vs nosql: how do you choose? with practical syntax and implementation patterns.

Answer

SQL vs NoSQL: how do you choose? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q43NoSQL database concepts

What is a document database?

Interview answer for what is a document database? with practical syntax and implementation patterns.

Answer

What is a document database? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q44NoSQL database concepts

What is a key-value database?

Interview answer for what is a key-value database? with practical syntax and implementation patterns.

Answer

What is a key-value database? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q51Caching fundamentals and strategies

What is caching and why use it?

Interview answer for what is caching and why use it? with practical syntax and implementation patterns.

Answer

What is caching and why use it? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q52Caching fundamentals and strategies

What is cache-aside (lazy loading)?

Interview answer for what is cache-aside (lazy loading)? with practical syntax and implementation patterns.

Answer

What is cache-aside (lazy loading)? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q56Caching fundamentals and strategies

What is a TTL?

Interview answer for what is a ttl? with practical syntax and implementation patterns.

Answer

What is a TTL? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q61Distributed caching and consistency

In-memory vs distributed cache

Interview answer for in-memory vs distributed cache with practical syntax and implementation patterns.

Answer

In-memory vs distributed cache is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q69Distributed caching and consistency

How do you measure cache hit ratio?

Interview answer for how do you measure cache hit ratio? with practical syntax and implementation patterns.

Answer

How do you measure cache hit ratio? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q72Reliability, operations, and tuning

What is a database replica?

Interview answer for what is a database replica? with practical syntax and implementation patterns.

Answer

What is a database replica? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.

Intermediate Questions

Implementation details, practical patterns, and common workflows.

Q6Relational database fundamentals

Explain 1NF, 2NF, and 3NF

Interview answer for explain 1nf, 2nf, and 3nf with practical syntax and implementation patterns.

Answer

Explain 1NF, 2NF, and 3NF is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q7Relational database fundamentals

What is denormalization and when is it useful?

Interview answer for what is denormalization and when is it useful? with practical syntax and implementation patterns.

Answer

What is denormalization and when is it useful? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q9Relational database fundamentals

What is transaction isolation?

Interview answer for what is transaction isolation? with practical syntax and implementation patterns.

Answer

What is transaction isolation? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q14SQL queries and transactions

What is a common table expression (CTE)?

Interview answer for what is a common table expression (cte)? with practical syntax and implementation patterns.

Answer

What is a common table expression (CTE)? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q15SQL queries and transactions

What are window functions?

Interview answer for what are window functions? with practical syntax and implementation patterns.

Answer

What are window functions? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q16SQL queries and transactions

How do you implement pagination efficiently?

Interview answer for how do you implement pagination efficiently? with practical syntax and implementation patterns.

Answer

How do you implement pagination efficiently? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

SELECT columns FROM table WHERE predicate ORDER BY sort_key LIMIT 20;

Example

Select only the columns you need, filter early, and use a deterministic ordering for pagination.

Code example

SELECT customer_id, COUNT(*) AS order_count
FROM orders
WHERE created_at >= DATE '2026-01-01'
GROUP BY customer_id
HAVING COUNT(*) > 5
ORDER BY order_count DESC
LIMIT 20;

Diagram

SQL → Parse/plan → Filter + join/aggregate → Sort/limit → Result set

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q19SQL queries and transactions

How do you use transactions safely?

Interview answer for how do you use transactions safely? with practical syntax and implementation patterns.

Answer

How do you use transactions safely? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q22Indexing and query performance

How does a B-tree index work?

Interview answer for how does a b-tree index work? with practical syntax and implementation patterns.

Answer

How does a B-tree index work? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q23Indexing and query performance

Clustered vs nonclustered indexes

Interview answer for clustered vs nonclustered indexes with practical syntax and implementation patterns.

Answer

Clustered vs nonclustered indexes is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q24Indexing and query performance

What is a composite index?

Interview answer for what is a composite index? with practical syntax and implementation patterns.

Answer

What is a composite index? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q25Indexing and query performance

What is index selectivity?

Interview answer for what is index selectivity? with practical syntax and implementation patterns.

Answer

What is index selectivity? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q26Indexing and query performance

When can an index hurt performance?

Interview answer for when can an index hurt performance? with practical syntax and implementation patterns.

Answer

When can an index hurt performance? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q27Indexing and query performance

How do you read an execution plan?

Interview answer for how do you read an execution plan? with practical syntax and implementation patterns.

Answer

How do you read an execution plan? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q29Indexing and query performance

How do you optimize a slow SQL query?

Interview answer for how do you optimize a slow sql query? with practical syntax and implementation patterns.

Answer

How do you optimize a slow SQL query? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q30Indexing and query performance

What is the N+1 query problem?

Interview answer for what is the n+1 query problem? with practical syntax and implementation patterns.

Answer

What is the N+1 query problem? is an important database and performance concept within indexing and query performance. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q34Relational data modeling

What is a surrogate key vs natural key?

Interview answer for what is a surrogate key vs natural key? with practical syntax and implementation patterns.

Answer

What is a surrogate key vs natural key? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q35Relational data modeling

How do you model soft deletes?

Interview answer for how do you model soft deletes? with practical syntax and implementation patterns.

Answer

How do you model soft deletes? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q36Relational data modeling

How should timestamps and time zones be stored?

Interview answer for how should timestamps and time zones be stored? with practical syntax and implementation patterns.

Answer

How should timestamps and time zones be stored? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q37Relational data modeling

What is a materialized view?

Interview answer for what is a materialized view? with practical syntax and implementation patterns.

Answer

What is a materialized view? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q39Relational data modeling

What are database migrations?

Interview answer for what are database migrations? with practical syntax and implementation patterns.

Answer

What are database migrations? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q45NoSQL database concepts

What is a wide-column database?

Interview answer for what is a wide-column database? with practical syntax and implementation patterns.

Answer

What is a wide-column database? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q46NoSQL database concepts

What is a graph database?

Interview answer for what is a graph database? with practical syntax and implementation patterns.

Answer

What is a graph database? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q47NoSQL database concepts

What is eventual consistency?

Interview answer for what is eventual consistency? with practical syntax and implementation patterns.

Answer

What is eventual consistency? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q50NoSQL database concepts

How do you design a NoSQL data model?

Interview answer for how do you design a nosql data model? with practical syntax and implementation patterns.

Answer

How do you design a NoSQL data model? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q53Caching fundamentals and strategies

What is write-through caching?

Interview answer for what is write-through caching? with practical syntax and implementation patterns.

Answer

What is write-through caching? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q55Caching fundamentals and strategies

What is read-through caching?

Interview answer for what is read-through caching? with practical syntax and implementation patterns.

Answer

What is read-through caching? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q57Caching fundamentals and strategies

What is cache invalidation?

Interview answer for what is cache invalidation? with practical syntax and implementation patterns.

Answer

What is cache invalidation? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q59Caching fundamentals and strategies

What is negative caching?

Interview answer for what is negative caching? with practical syntax and implementation patterns.

Answer

What is negative caching? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q60Caching fundamentals and strategies

How do you choose a cache key?

Interview answer for how do you choose a cache key? with practical syntax and implementation patterns.

Answer

How do you choose a cache key? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q62Distributed caching and consistency

How does Redis differ from a local memory cache?

Interview answer for how does redis differ from a local memory cache? with practical syntax and implementation patterns.

Answer

How does Redis differ from a local memory cache? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q63Distributed caching and consistency

How do you invalidate cache after a database update?

Interview answer for how do you invalidate cache after a database update? with practical syntax and implementation patterns.

Answer

How do you invalidate cache after a database update? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q67Distributed caching and consistency

How do you cache API responses safely?

Interview answer for how do you cache api responses safely? with practical syntax and implementation patterns.

Answer

How do you cache API responses safely? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q70Distributed caching and consistency

How do you avoid caching user-specific data incorrectly?

Interview answer for how do you avoid caching user-specific data incorrectly? with practical syntax and implementation patterns.

Answer

How do you avoid caching user-specific data incorrectly? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q71Reliability, operations, and tuning

How do connection pools work?

Interview answer for how do connection pools work? with practical syntax and implementation patterns.

Answer

How do connection pools work? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q73Reliability, operations, and tuning

Read replicas vs write primary

Interview answer for read replicas vs write primary with practical syntax and implementation patterns.

Answer

Read replicas vs write primary is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q74Reliability, operations, and tuning

What are backup, restore, and point-in-time recovery?

Interview answer for what are backup, restore, and point-in-time recovery? with practical syntax and implementation patterns.

Answer

What are backup, restore, and point-in-time recovery? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q75Reliability, operations, and tuning

How do you monitor database performance?

Interview answer for how do you monitor database performance? with practical syntax and implementation patterns.

Answer

How do you monitor database performance? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q76Reliability, operations, and tuning

How do you detect slow queries in production?

Interview answer for how do you detect slow queries in production? with practical syntax and implementation patterns.

Answer

How do you detect slow queries in production? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q79Reliability, operations, and tuning

How do you test cache correctness and performance?

Interview answer for how do you test cache correctness and performance? with practical syntax and implementation patterns.

Answer

How do you test cache correctness and performance? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.

Advanced Questions

Architecture, optimization, and design trade-offs.

Q10Relational database fundamentals

What is a database deadlock?

Interview answer for what is a database deadlock? with practical syntax and implementation patterns.

Answer

What is a database deadlock? is an important database and performance concept within relational database fundamentals. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q17SQL queries and transactions

What is optimistic concurrency control?

Interview answer for what is optimistic concurrency control? with practical syntax and implementation patterns.

Answer

What is optimistic concurrency control? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q18SQL queries and transactions

What is pessimistic locking?

Interview answer for what is pessimistic locking? with practical syntax and implementation patterns.

Answer

What is pessimistic locking? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q20SQL queries and transactions

What is a database isolation anomaly?

Interview answer for what is a database isolation anomaly? with practical syntax and implementation patterns.

Answer

What is a database isolation anomaly? is an important database and performance concept within sql queries and transactions. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q38Relational data modeling

What is table partitioning?

Interview answer for what is table partitioning? with practical syntax and implementation patterns.

Answer

What is table partitioning? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q40Relational data modeling

How do you avoid schema-change downtime?

Interview answer for how do you avoid schema-change downtime? with practical syntax and implementation patterns.

Answer

How do you avoid schema-change downtime? is an important database and performance concept within relational data modeling. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q48NoSQL database concepts

What is the CAP theorem?

Interview answer for what is the cap theorem? with practical syntax and implementation patterns.

Answer

What is the CAP theorem? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q49NoSQL database concepts

What is sharding?

Interview answer for what is sharding? with practical syntax and implementation patterns.

Answer

What is sharding? is an important database and performance concept within nosql database concepts. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

// Document-style record
{ "_id": "p-42", "name": "Desk lamp", "category": "lighting" }

Example

Choose a model based on access patterns: document records for aggregate reads, key-value for direct lookups, graph for relationship traversals.

Code example

// MongoDB-style query (illustrative)
const product = await db.collection("products").findOne({
  _id: "p-42",
});
await db.collection("products").createIndex({ category: 1, name: 1 });

Diagram

Application access patterns → Data model + partition key → NoSQL store → Query results

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q54Caching fundamentals and strategies

What is write-behind caching?

Interview answer for what is write-behind caching? with practical syntax and implementation patterns.

Answer

What is write-behind caching? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q58Caching fundamentals and strategies

What is a cache stampede?

Interview answer for what is a cache stampede? with practical syntax and implementation patterns.

Answer

What is a cache stampede? is an important database and performance concept within caching fundamentals and strategies. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q64Distributed caching and consistency

What is stale-while-revalidate?

Interview answer for what is stale-while-revalidate? with practical syntax and implementation patterns.

Answer

What is stale-while-revalidate? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q65Distributed caching and consistency

How do you prevent cache penetration?

Interview answer for how do you prevent cache penetration? with practical syntax and implementation patterns.

Answer

How do you prevent cache penetration? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q66Distributed caching and consistency

What is a cache avalanche?

Interview answer for what is a cache avalanche? with practical syntax and implementation patterns.

Answer

What is a cache avalanche? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q68Distributed caching and consistency

How do you handle cache failures?

Interview answer for how do you handle cache failures? with practical syntax and implementation patterns.

Answer

How do you handle cache failures? is an important database and performance concept within distributed caching and consistency. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

GET cache:key; SET cache:key value EX 300

Example

Cache frequently requested data for a bounded period, and define how writes invalidate or refresh the cached value.

Code example

// Cache-aside pattern (illustrative TypeScript)
const key = `product:${productId}`;
const cached = await cache.get(key);
if (cached !== null) return JSON.parse(cached);

const product = await repository.findById(productId);
if (!product) {
  await cache.set(key, "__missing__", { ttlSeconds: 30 });
  return null;
}
await cache.set(key, JSON.stringify(product), { ttlSeconds: 300 });
return product;

Diagram

Request → Cache lookup ─hit→ Return value
                  └miss→ Database → Populate cache → Return value

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q77Reliability, operations, and tuning

How do you tune connection pool size?

Interview answer for how do you tune connection pool size? with practical syntax and implementation patterns.

Answer

How do you tune connection pool size? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE TABLE example (id BIGINT PRIMARY KEY, name TEXT NOT NULL);

Example

Start from the access patterns and integrity requirements, then choose constraints and schema that make invalid states difficult to represent.

Code example

CREATE TABLE customers (
  id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  email TEXT NOT NULL UNIQUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);

SELECT id, email
FROM customers
WHERE email = $1;

Diagram

Application → Connection pool → Database engine → Constraints/transaction → Result

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q78Reliability, operations, and tuning

How should retry logic handle transient database errors?

Interview answer for how should retry logic handle transient database errors? with practical syntax and implementation patterns.

Answer

How should retry logic handle transient database errors? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

BEGIN; -- statements; COMMIT;  (ROLLBACK on failure)

Example

Group related updates into a transaction and keep the transaction short to reduce lock duration and deadlock risk.

Code example

await db.transaction(async (tx) => {
  await tx.accounts.debit(fromAccountId, amount);
  await tx.accounts.credit(toAccountId, amount);
});

Diagram

BEGIN → Read/check invariants → Write changes → COMMIT
                         └failure/deadlock→ ROLLBACK/retry safely

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.
Q80Reliability, operations, and tuning

How do you choose indexes for a real workload?

Interview answer for how do you choose indexes for a real workload? with practical syntax and implementation patterns.

Answer

How do you choose indexes for a real workload? is an important database and performance concept within reliability, operations, and tuning. The best design depends on the application's access patterns, data volume, consistency requirements, and operational constraints. Measure the real workload before changing schemas, indexes, or cache policy; validate improvements with representative data and execution plans. Keep correctness first: caching and performance optimizations must not bypass authorization or data-integrity rules.

Syntax

CREATE INDEX idx_orders_customer_created ON orders(customer_id, created_at DESC);

Example

For a frequent customer order-history query, index the filtering column first and the ordering column next when that matches the workload.

Code example

-- Example query and supporting index (PostgreSQL-style)
CREATE INDEX idx_orders_customer_created
  ON orders (customer_id, created_at DESC);

EXPLAIN ANALYZE
SELECT id, created_at, total
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC
LIMIT 20;

Diagram

SQL query → Planner + statistics → Chosen plan → Index/table access → Rows returned

Key Points

  • Start with the actual query or access pattern and its latency/throughput target.
  • Use representative production-like data and inspect metrics or execution plans.
  • Account for consistency, invalidation, failure handling, and operational cost.
  • Add tests for edge cases and verify that the optimization preserves correctness.

Share this question bank

Send this page to someone preparing for an interview.