Senior & Lead Engineer
Interview Mastery Hub
100 real-world, scenario-based architecture & concurrency questions designed for 5–10+ years experienced developers. Free & open for every student and engineer.
100
Real-world Q&As
100%
Scenario-Based
5-10 Yrs
Senior / Lead Depth
5 Stacks
Core Technologies
Showing 100 questions for senior interview preparation
How do you handle Cache Stampede (Dog-Piling) in Laravel when high-traffic cache keys expire simultaneously?
The Cache Stampede Problem
When a hot cache item expires, hundreds of incoming concurrent threads miss the cache at the exact same millisecond and all attempt to compute the expensive query and write back to cache simultaneously.
Solution 1: Cache::flexible() in Modern Laravel
Laravel provides stale-while-revalidate out of the box:
$stats = Cache::flexible('homepage_stats', [300, 600], function () {
return DB::table('orders')->selectRaw('count(*), sum(amount)')->first();
});
// Serves stale cache instantly while dispatching background regeneration after 300s
Solution 2: Atomic Cache Locking (Cache::lock)
$data = Cache::get('homepage_stats');
if (! $data) {
$lock = Cache::lock('lock:homepage_stats', 10);
if ($lock->get()) {
try {
$data = ComputeExpensiveStats();
Cache::put('homepage_stats', $data, now()->addMinutes(10));
} finally {
$lock->release();
}
} else {
// Sleep briefly and read cache populated by the winning thread
usleep(200000);
$data = Cache::get('homepage_stats');
}
}
How does Type Juggling and Strict Typing (`declare(strict_types=1);`) affect function returns, arrays, and coercion in PHP 8.x?
File-Level Scope of strict_types
declare(strict_types=1); is per-file and affects function calls made FROM that specific file, not the file declaring the function.
- If File A has
strict_types=1and callscalculateTax("100.50"), PHP throwsTypeError. - If File B does NOT have
strict_types=1and calls the samecalculateTax("100.50"), PHP coerces the string to float100.50. - Best practice: Enforce
declare(strict_types=1);across all project files via code standards tools (PHP-CS-Fixer / Pint).
How does Covering Index eliminate Bookmark Lookups to achieve sub-millisecond query performance?
Covering Index (Using index)
When all columns requested in SELECT, WHERE, and ORDER BY exist within the secondary index itself, MySQL retrieves data directly from the index in RAM without touching table row data on disk.
CREATE INDEX idx_users_org_email_date ON users (org_id, email, created_at);
Query: SELECT email, created_at FROM users WHERE org_id = 10; is 100% satisfied by the index.
How does `EXPLAIN (ANALYZE, BUFFERS)` reveal Shared Hit vs Shared Read disk IO bottlenecks?
Analyzing BUFFERS Metrics
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM accounts WHERE balance > 50000;
shared hit=5000: 5,000 data blocks were read directly from RAM (Shared Buffers cache) with zero disk latency.shared read=8000: 8,000 blocks had to be fetched from physical disk or OS filesystem cache.
How do you implement Async Worker Retries with Exponential Backoff and Dead Letter Queues (DLQ)?
Exponential Backoff with Jitter
$retryDelay = min(3600, pow(2, $attemptCount) * 10 + rand(0, 5));
- Attempt 1: 20s
- Attempt 2: 40s
- Attempt 3: 80s
- Max Retries Exceeded: Route the failed payload to a Dead Letter Queue (DLQ) for automated alerting and manual developer replay.
Explain the architectural differences between Laravel Events vs. Model Observers vs. Action Classes.
Comparison Matrix
| Pattern | Best Used For | Warning / Anti-Pattern |
|---|---|---|
| Model Observers | Passive lifecycle tracking (Audit logs, cache clearing, slug auto-generation) | Calling external APIs or triggering billing inside observers. Observers fire during seeders/batch updates and are hard to trace. |
| Events & Listeners | Asynchronous, cross-boundary side effects (Sending email after order placed, push notifications) | Synchronous coupling where the caller expects immediate return value. |
| Action Classes (Single Responsibility) | Core domain business operations (e.g. RegisterUserAction, ProcessRefundAction) |
Keep business logic testable and explicit with typed parameters. |
How do you profile PHP performance bottlenecks, CPU cycles, and memory consumption using Blackfire, Xhprof, and SPX?
Profiling Methodology
- Instrument with SPX / Xhprof: Generates a Call Graph tracking:
- Wall time vs CPU time
- Memory peak allocations per function call
- Function invocation count
- Common Culprits:
- Deep nested loops hydrating arrays into domain objects.
- Repetitive serialization / JSON parsing.
- Autoloader filesystem IO when APCu/OPcache is misconfigured.
Explain the 4 Transaction Isolation Levels in MySQL and the anomalies they prevent (Dirty Read, Non-Repeatable Read, Phantom Read).
ACID Isolation Levels
| Level | Dirty Read | Non-Repeatable Read | Phantom Read | Default In |
|---|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible | - |
| READ COMMITTED | Prevented | Possible | Possible | Postgres / Oracle |
| REPEATABLE READ | Prevented | Prevented | Prevented (via MVCC/Gap Lock) | MySQL InnoDB |
| SERIALIZABLE | Prevented | Prevented | Prevented | Strict Financials |
How does PostgreSQL Foreign Data Wrapper (`postgres_fdw`) enable cross-database federated queries?
Configuring postgres_fdw
CREATE EXTENSION postgres_fdw;
CREATE SERVER billing_server
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (host '10.0.0.50', dbname 'billing_db', port '5432');
CREATE USER MAPPING FOR current_user
SERVER billing_server
OPTIONS (user 'db_reader', password 'secret');
IMPORT FOREIGN SCHEMA public FROM SERVER billing_server INTO foreign_billing;
-- Query local and remote tables seamlessly in a single SQL statement
SELECT c.name, b.invoice_total
FROM customers c
JOIN foreign_billing.invoices b ON c.id = b.customer_id;
How do you design a High-Scale Distributed Counter for Millions of Video Views or Upvotes?
Sharded Counters / Write-Back Buffering
- Redis Atomic Increment:
Redis::incr("video:views:{$videoId}"); - Batch Flusher Daemon: Every 10 seconds, a background worker consumes the aggregated count from Redis via
INCRBYand writes a single consolidated SQL update:UPDATE videos SET views = views + 5000 WHERE id = 5;
Reduces database write operations by 99.9%.
How do you safely scale Laravel Horizon with Redis Clusters when handling 50,000 jobs per minute?
Redis Cluster Hash Tag Pinning
In Redis Cluster, commands operating on multiple keys (like atomic queue pops) require all keys to reside on the same cluster node. Use Redis Hash Tags {horizon}:
'prefix' => '{horizon}:',
This forces all related Horizon state keys into the same hash slot, eliminating MOVED cluster exceptions while scaling workers seamlessly across nodes.
Explain the difference between `Pdo` connection pooling vs persistent connections (`PDO::ATTR_PERSISTENT`) in PHP-FPM.
The Persistent Connection Danger in PHP-FPM
With PDO::ATTR_PERSISTENT, each PHP-FPM worker process keeps its own persistent database connection open even after the request terminates.
- If you have 500 PHP-FPM workers across 4 web servers, that equals 2,000 persistent idle database connections.
- Solution: Use dedicated external connection poolers (like ProxySQL for MySQL or PgBouncer for PostgreSQL) rather than in-process persistent PDO connections.
How do you identify and resolve Deadlocks using `SHOW ENGINE INNODB STATUS`?
Analyzing LATEST DETECTED DEADLOCK
Run:
SHOW ENGINE INNODB STATUS\G
Look for:
(1) TRANSACTIONvs(2) TRANSACTIONLOCK WAITstatementsRECORD LOCKS space id ... lock_mode X- Identify which transaction was chosen as the deadlock victim and rolled back based on the lowest number of modified rows.
What is the purpose of WAL (Write-Ahead Log) archiving and Point-In-Time Recovery (PITR)?
PITR Recovery Workflow
- Restore the most recent physical base backup (e.g. pgBackRest / WAL-G).
- Set
recovery_target_time = '2026-08-27 14:32:05 UTC'. - PostgreSQL replays archived WAL segments up to the exact target second and halts replay before the destructive command.
How does Consistent Hashing minimize data movement during Cache Cluster node addition or removal?
Consistent Hashing Ring
- Maps both Cache Servers and Keys onto a 360-degree circular hash ring (e.g. 0 to $2^{32}-1$).
- A key is assigned to the nearest server located clockwise on the ring.
- When a server is added or removed, only $K/N$ keys need remapping, preventing total cache thrashing.
- Virtual Nodes: Assigns multiple virtual points per physical server to ensure even distribution across nodes.
How do you implement Idempotent API endpoints in Laravel to prevent duplicate charges upon client network retries?
Idempotency Key Middleware Implementation
class EnsureIdempotency
{
public function handle(Request $request, Closure $next): Response
{
$idempotencyKey = $request->header('Idempotency-Key');
if (! $idempotencyKey) {
return response()->json(['error' => 'Idempotency-Key header is required'], 400);
}
$cacheKey = "idempotency:{$request->user()->id}:{$idempotencyKey}";
$lock = Cache::lock("lock:{$cacheKey}", 15);
if (! $lock->get()) {
return response()->json(['error' => 'Concurrent request in progress'], 409);
}
if ($cachedResponse = Cache::get($cacheKey)) {
$lock->release();
return response()->json($cachedResponse['data'], $cachedResponse['status']);
}
$response = $next($request);
if ($response->isSuccessful()) {
Cache::put($cacheKey, [
'data' => json_decode($response->getContent(), true),
'status' => $response->getStatusCode(),
], now()->addHours(24));
}
$lock->release();
return $response;
}
}
How does the Match Expression differ internally from the Switch Statement in PHP 8.x?
match vs switch Differences
- Strict Comparison:
matchuses===identity matching;switchuses loose==comparison. - Returns a Value:
matchis an expression that evaluates directly to a result. - No Fallthrough:
matchdoes not requirebreak;statements. - Exhaustive Matching: Throws
UnhandledMatchErrorif no branch matches and nodefaultis specified.
Why does `SELECT COUNT(*)` on InnoDB scan the entire primary key tree unlike MyISAM?
Why InnoDB Cannot Store an Exact Row Count
Because InnoDB uses MVCC (Multi-Version Concurrency Control), different concurrent transactions see different numbers of visible rows at the exact same moment.
- MyISAM locked tables and stored a single counter, but did not support transactions.
- Solution for Large Tables: Use Redis cached counters or query
information_schema.TABLES.TABLE_ROWSfor approximations.
How does `pg_stat_statements` identify the most resource-intensive SQL queries across your entire database cluster?
Querying pg_stat_statements
SELECT query, calls, total_exec_time / 1000 as total_seconds,
mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 5;
Provides normalized query text, execution counts, and total CPU time consumed.
Explain the Difference between Polling, Long-Polling, Server-Sent Events (SSE), and WebSockets.
Protocol Comparison
| Protocol | Direction | Overhead | Ideal Use Case |
|---|---|---|---|
| Short Polling | Client -> Server | High (repetitive HTTP headers) | Simple status checks |
| Long Polling | Client -> Server (held open) | Medium | Fallback when WebSockets blocked |
| Server-Sent Events (SSE) | Server -> Client Only | Very Low (Standard HTTP) | Live Feed, Stock Tickers, AI Streaming text |
| WebSockets | Full Duplex Bi-directional | Minimal (Single TCP handshake) | Multiplayer Games, Chat, Collaborative Editing |