Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
Open-Access Production Interview Prep

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

•
Laravel Advanced & Architecture 8-10 Years (Tech Lead) Hard Production Scenario

How do you handle Cache Stampede (Dog-Piling) in Laravel when high-traffic cache keys expire simultaneously?

Incident Scenario: When the home page top banner cache expired at midnight, 5,000 concurrent requests simultaneously hammered MySQL with the exact same complex aggregation query, bringing the primary database server CPU to 100%.
257 views • Direct Permalink

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');
    }
}
Tags: #Cache Stampede #Redis #Atomic Locks #Dog-Piling #High Traffic
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How does Type Juggling and Strict Typing (`declare(strict_types=1);`) affect function returns, arrays, and coercion in PHP 8.x?

Incident Scenario: An automated billing function passed a string `"100.50"` to a float parameter. In one file it worked, but in another it threw a `TypeError`.
799 views • Direct Permalink

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=1 and calls calculateTax("100.50"), PHP throws TypeError.
  • If File B does NOT have strict_types=1 and calls the same calculateTax("100.50"), PHP coerces the string to float 100.50.
  • Best practice: Enforce declare(strict_types=1); across all project files via code standards tools (PHP-CS-Fixer / Pint).
Tags: #Strict Types #Type Juggling #TypeError #PHP 8
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Medium Production Scenario

How does Covering Index eliminate Bookmark Lookups to achieve sub-millisecond query performance?

Incident Scenario: A dashboard query fetching user email and created date was reading millions of rows from disk.
174 views • Direct Permalink

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.

Tags: #Covering Index #Index Only Scan #Performance
PostgreSQL Enterprise & Performance 5-8 Years (Senior) Hard Production Scenario

How does `EXPLAIN (ANALYZE, BUFFERS)` reveal Shared Hit vs Shared Read disk IO bottlenecks?

Incident Scenario: Determining whether a slow query is CPU-bound or waiting for disk pages to be loaded into PostgreSQL shared buffers.
512 views • Direct Permalink

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.
Tags: #EXPLAIN BUFFERS #Shared Buffers #IO Performance
System Design, Redis & Distributed Systems 5-8 Years (Senior) Medium Production Scenario

How do you implement Async Worker Retries with Exponential Backoff and Dead Letter Queues (DLQ)?

Incident Scenario: A bank webhook was temporarily offline; retrying failed webhook jobs every 1 second overwhelmed the receiving server and wasted CPU cycles.
552 views • Direct Permalink

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.
Tags: #Dead Letter Queue #Exponential Backoff #Queues #Resilience
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

Explain the architectural differences between Laravel Events vs. Model Observers vs. Action Classes.

Incident Scenario: In a team of 15 engineers, business logic was scattered between Eloquent observers, listeners, and fat controllers, causing unintended side effects during seeding and batch imports.
796 views • Direct Permalink

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.
Tags: #Domain Architecture #Events #Observers #Action Classes #Clean Code
Modern PHP 8.x & Internals 8-10 Years (Tech Lead) Hard Production Scenario

How do you profile PHP performance bottlenecks, CPU cycles, and memory consumption using Blackfire, Xhprof, and SPX?

Incident Scenario: An endpoint takes 3.8s in production. Logs show database queries only account for 200ms. Where is the remaining 3.6s spent?
228 views • Direct Permalink

Profiling Methodology

  1. Instrument with SPX / Xhprof: Generates a Call Graph tracking:
    • Wall time vs CPU time
    • Memory peak allocations per function call
    • Function invocation count
  2. Common Culprits:
    • Deep nested loops hydrating arrays into domain objects.
    • Repetitive serialization / JSON parsing.
    • Autoloader filesystem IO when APCu/OPcache is misconfigured.
Tags: #Profiling #Blackfire #Xhprof #SPX #Benchmarking
MySQL Tuning, Indexing & Concurrency 8-10 Years (Tech Lead) Hard Production Scenario

Explain the 4 Transaction Isolation Levels in MySQL and the anomalies they prevent (Dirty Read, Non-Repeatable Read, Phantom Read).

Incident Scenario: An accounting team discovered discrepancies in financial balances generated during concurrent ledger updates.
587 views • Direct Permalink

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
Tags: #Isolation Levels #ACID #Transactions #Concurrency
PostgreSQL Enterprise & Performance 8-10 Years (Tech Lead) Hard Production Scenario

How does PostgreSQL Foreign Data Wrapper (`postgres_fdw`) enable cross-database federated queries?

Incident Scenario: Joining customer CRM data stored in PostgreSQL Database A with billing records stored in PostgreSQL Database B.
793 views • Direct Permalink

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;
Tags: #postgres_fdw #Foreign Data Wrapper #Federated Queries
System Design, Redis & Distributed Systems 8-10 Years (Tech Lead) Hard Production Scenario

How do you design a High-Scale Distributed Counter for Millions of Video Views or Upvotes?

Incident Scenario: Directly updating `UPDATE videos SET views = views + 1 WHERE id = 5` under 50,000 views/sec caused database row lock saturation.
331 views • Direct Permalink

Sharded Counters / Write-Back Buffering

  1. Redis Atomic Increment:
    Redis::incr("video:views:{$videoId}");
    
  2. Batch Flusher Daemon: Every 10 seconds, a background worker consumes the aggregated count from Redis via INCRBY and writes a single consolidated SQL update:
    UPDATE videos SET views = views + 5000 WHERE id = 5;
    

Reduces database write operations by 99.9%.

Tags: #Counters #Redis INCRBY #Write-Back Cache #High Concurrency
Laravel Advanced & Architecture 8-10 Years (Tech Lead) Hard Production Scenario

How do you safely scale Laravel Horizon with Redis Clusters when handling 50,000 jobs per minute?

Incident Scenario: Redis memory was saturated and Horizon workers threw "MOVED" cluster errors because queue keys were not mapped to the same hash slot in a multi-node Redis cluster.
432 views • Direct Permalink

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.

Tags: #Horizon #Redis Cluster #Hash Tags #DevOps #Scaling
Modern PHP 8.x & Internals 8-10 Years (Tech Lead) Hard Production Scenario

Explain the difference between `Pdo` connection pooling vs persistent connections (`PDO::ATTR_PERSISTENT`) in PHP-FPM.

Incident Scenario: Under 5,000 req/sec, MySQL threw "Too many connections" (Error 1040) while PHP-FPM was configured with `PDO::ATTR_PERSISTENT => true`.
691 views • Direct Permalink

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.
Tags: #PDO #Persistent Connections #Connection Pooling #MySQL
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Hard Production Scenario

How do you identify and resolve Deadlocks using `SHOW ENGINE INNODB STATUS`?

Incident Scenario: Production logs report MySQL error 1213. You need to extract the exact queries, locks, and transactions involved.
742 views • Direct Permalink

Analyzing LATEST DETECTED DEADLOCK

Run:

SHOW ENGINE INNODB STATUS\G

Look for:

  • (1) TRANSACTION vs (2) TRANSACTION
  • LOCK WAIT statements
  • RECORD 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.
Tags: #Deadlocks #InnoDB Status #Debugging
PostgreSQL Enterprise & Performance 8-10 Years (Tech Lead) Hard Production Scenario

What is the purpose of WAL (Write-Ahead Log) archiving and Point-In-Time Recovery (PITR)?

Incident Scenario: A developer accidentally executed a `DROP TABLE` at 14:32:10. How do you restore the database to 14:32:05 with zero lost data?
639 views • Direct Permalink

PITR Recovery Workflow

  1. Restore the most recent physical base backup (e.g. pgBackRest / WAL-G).
  2. Set recovery_target_time = '2026-08-27 14:32:05 UTC'.
  3. PostgreSQL replays archived WAL segments up to the exact target second and halts replay before the destructive command.
Tags: #WAL Archiving #PITR #Disaster Recovery #Backup
System Design, Redis & Distributed Systems 10+ Years (Principal / Architect) Hard Production Scenario

How does Consistent Hashing minimize data movement during Cache Cluster node addition or removal?

Incident Scenario: Adding a 5th Memcached server caused 80% of existing cache keys to remap and miss simultaneously using standard `hash(key) % N`.
785 views • Direct Permalink

Consistent Hashing Ring

  1. Maps both Cache Servers and Keys onto a 360-degree circular hash ring (e.g. 0 to $2^{32}-1$).
  2. A key is assigned to the nearest server located clockwise on the ring.
  3. When a server is added or removed, only $K/N$ keys need remapping, preventing total cache thrashing.
  4. Virtual Nodes: Assigns multiple virtual points per physical server to ensure even distribution across nodes.
Tags: #Consistent Hashing #Virtual Nodes #Caching #Distributed Systems
Laravel Advanced & Architecture 5-8 Years (Senior) Hard Production Scenario

How do you implement Idempotent API endpoints in Laravel to prevent duplicate charges upon client network retries?

Incident Scenario: A mobile client with poor connectivity sent 3 consecutive `POST /api/v1/payments` requests with the same card payload when the network timed out, causing the customer to be billed 3 times.
370 views • Direct Permalink

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;
    }
}
Tags: #API Design #Idempotency #Payments #Security #Resilience
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How does the Match Expression differ internally from the Switch Statement in PHP 8.x?

Incident Scenario: A legacy `switch` statement comparing string `"0"` with integer `0` caused security bypasses.
257 views • Direct Permalink

match vs switch Differences

  1. Strict Comparison: match uses === identity matching; switch uses loose == comparison.
  2. Returns a Value: match is an expression that evaluates directly to a result.
  3. No Fallthrough: match does not require break; statements.
  4. Exhaustive Matching: Throws UnhandledMatchError if no branch matches and no default is specified.
Tags: #Match Expression #Switch #Type Safety #PHP 8
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Medium Production Scenario

Why does `SELECT COUNT(*)` on InnoDB scan the entire primary key tree unlike MyISAM?

Incident Scenario: Executing `SELECT COUNT(*) FROM orders` on a 50-million row InnoDB table took 12 seconds.
766 views • Direct Permalink

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_ROWS for approximations.
Tags: #COUNT #InnoDB #MVCC #Performance
PostgreSQL Enterprise & Performance 5-8 Years (Senior) Medium Production Scenario

How does `pg_stat_statements` identify the most resource-intensive SQL queries across your entire database cluster?

Incident Scenario: Identifying top 5 slowest queries across 1,000 requests/sec without enabling heavy slow query logging.
714 views • Direct Permalink

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.

Tags: #pg_stat_statements #Monitoring #Query Profiling
System Design, Redis & Distributed Systems 5-8 Years (Senior) Medium Production Scenario

Explain the Difference between Polling, Long-Polling, Server-Sent Events (SSE), and WebSockets.

Incident Scenario: Selecting the most efficient realtime communication protocol for live stock price tickers vs bi-directional collaborative canvas editing.
48 views • Direct Permalink

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
Tags: #SSE #WebSockets #Long Polling #Protocols