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 10+ Years (Principal / Architect) Expert Production Scenario

How do you configure and optimize Laravel for High-Concurrency Microservices using gRPC and HTTP/2?

Incident Scenario: Microservices communicating via JSON over HTTP/1.1 experienced serialization bottlenecks and TCP connection exhaustion under 15,000 RPS internal traffic.
791 views • Direct Permalink

gRPC with Protocol Buffers in PHP

  1. Binary Serialization vs JSON: Protocol Buffers serialize payloads into compact binary format, reducing payload size by 70% and CPU deserialization time by 80%.
  2. HTTP/2 Multiplexing: Multiple bidirectional gRPC RPC calls share a single persistent TCP connection, preventing ephemeral port exhaustion.
  3. RoadRunner gRPC Plugin: Run Laravel worker processes through Spiral RoadRunner gRPC server for native C-level gRPC transport.
Tags: #Microservices #gRPC #HTTP/2 #Protobuf #High Throughput
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How do Enums in PHP 8.1+ support Backed Values, Methods, and Interfaces?

Incident Scenario: Replacing string literals in status workflows with type-safe Enums that provide UI labels, colors, and transition validations.
392 views • Direct Permalink

Backed Enum with Methods & Traits

enum OrderStatus: string implements HasLabel
{
    case PENDING = 'pending';
    case PROCESSING = 'processing';
    case COMPLETED = 'completed';
    case CANCELLED = 'cancelled';

    public function label(): string
    {
        return match($this) {
            self::PENDING => 'Awaiting Payment',
            self::PROCESSING => 'In Progress',
            self::COMPLETED => 'Order Delivered',
            self::CANCELLED => 'Order Cancelled',
        };
    }

    public function canCancel(): bool
    {
        return in_array($this, [self::PENDING, self::PROCESSING], true);
    }
}
Tags: #Enums #Backed Enums #Type Safety #OOP
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Medium Production Scenario

How do Generated (Virtual & Stored) Columns and Functional Indexes optimize queries in MySQL 8?

Incident Scenario: Searching through a JSON column `details->>"$.customer_code"` was executing full table scans.
632 views • Direct Permalink

Functional Index on JSON Expressions

ALTER TABLE orders ADD INDEX idx_customer_code ((CAST(details->>'$.customer_code' AS CHAR(30))));

MySQL 8 allows indexing expressions directly without needing stored physical columns.

Tags: #MySQL 8 #JSON #Generated Columns #Functional Index
PostgreSQL Enterprise & Performance 5-8 Years (Senior) Medium Production Scenario

How do you perform Zero-Downtime Index Creation in PostgreSQL using `CONCURRENTLY`?

Incident Scenario: Creating an index on a 40M row production table threw timeout errors and locked incoming user registrations.
89 views • Direct Permalink

CREATE INDEX CONCURRENTLY

Standard CREATE INDEX takes an ACCESS EXCLUSIVE lock blocking writes.

CREATE INDEX CONCURRENTLY idx_users_email ON users (email);
  • Scans table twice and builds the index without blocking INSERT/UPDATE/DELETE operations.
  • Note: Cannot run inside a multi-statement transaction block.
Tags: #CREATE INDEX CONCURRENTLY #Zero Downtime #PostgreSQL
System Design, Redis & Distributed Systems 10+ Years (Principal / Architect) Expert Production Scenario

How do you design a Resilient Multi-Region Disaster Recovery architecture (Active-Active vs Active-Passive)?

Incident Scenario: Ensuring a SaaS application survives a complete AWS region outage with under 1 minute Recovery Time Objective (RTO) and zero Recovery Point Objective (RPO).
440 views • Direct Permalink

Active-Active vs Active-Passive

  • Active-Passive (Warm Standby): Primary region handles 100% traffic. Secondary region replicates data. DNS failover (Route 53) flips traffic if primary fails. RTO: 2-5 mins.
  • Active-Active (Multi-Region): Both US-East and EU-Central serve local traffic. Requires globally distributed conflict-free replicated data types (CRDTs) or distributed database like CockroachDB / Spanner.
Tags: #Disaster Recovery #Active-Active #RTO/RPO #Multi-Region
Laravel Advanced & Architecture 5-8 Years (Senior) Hard Production Scenario

How do you handle Dynamic Database Connection Routing (Read/Write Splitting) and Replica Lag in Laravel?

Incident Scenario: After a user updated their profile, they were redirected back to the profile page and saw their old data because the read query hit a MySQL replica with 400ms replication lag.
447 views • Direct Permalink

Sticky Connections in Laravel config/database.php

Enable the sticky option:

'mysql' => [
    'read' => [
        'host' => ['192.168.1.10', '192.168.1.11'],
    ],
    'write' => [
        'host' => ['192.168.1.5'],
    ],
    'sticky' => true, // Reads in the same request/lifecycle immediately route to Write DB
],

Force Primary Read on Critical Reads:

$user = User::onWriteConnection()->find($id);
Tags: #Read Write Splitting #Replication Lag #Database #High Availability
Modern PHP 8.x & Internals 8-10 Years (Tech Lead) Hard Production Scenario

How do you implement and verify Cryptographic Signatures (HMAC-SHA256) with timing attack prevention in PHP?

Incident Scenario: An attacker forged webhook authentication payloads because the signature check used standard `==` string comparison instead of `hash_equals()`.
717 views • Direct Permalink

Timing Attacks & Constant-Time String Comparison

Standard string comparisons (===) fail fast at the first differing byte. An attacker measuring millisecond response timing can deduce character by character.

$computedSignature = hash_hmac('sha256', $rawPayload, $secretKey);

// VULNERABLE to timing attacks:
// if ($computedSignature === $incomingSignature) { ... }

// SECURE constant-time verification:
if (! hash_equals($computedSignature, $incomingSignature)) {
    throw new SecurityException("Invalid webhook signature.");
}
Tags: #Security #Cryptography #Timing Attack #HMAC #hash_equals
MySQL Tuning, Indexing & Concurrency 8-10 Years (Tech Lead) Hard Production Scenario

How does `innodb_flush_log_at_trx_commit` trade ACID durability for 10x write throughput?

Incident Scenario: A high-speed IoT ingestion pipeline writing 20,000 metrics per second was bottlenecked by disk IOPS.
116 views • Direct Permalink

innodb_flush_log_at_trx_commit Settings

  • 1 (Default / Strict ACID): Redo log is flushed to disk on every single transaction commit. Maximum safety, high disk IOPS.
  • 2: Redo log is written to OS cache on commit and flushed to disk once per second. If OS crashes, at most 1 second of data is lost, but write throughput increases up to 10x.
  • 0: Flushed once per second in memory.
Tags: #ACID #Redo Log #IOPS #Tuning
PostgreSQL Enterprise & Performance 8-10 Years (Tech Lead) Hard Production Scenario

Explain CTE Optimization Fencing (`AS MATERIALIZED` vs `AS NOT MATERIALIZED`) in PostgreSQL 12+.

Incident Scenario: A complex query using Common Table Expressions ran 10x slower because the optimizer materialized intermediate result sets.
211 views • Direct Permalink

Controlling CTE Inlining

  • WITH my_cte AS NOT MATERIALIZED (...): Forces the query planner to inline the CTE directly into the parent query, allowing index pushdown and filter sharing.
  • WITH my_cte AS MATERIALIZED (...): Forces PostgreSQL to compute the CTE once into a temporary buffer, preventing repetitive recalculation if referenced multiple times.
Tags: #CTE #MATERIALIZED #Query Optimizer
System Design, Redis & Distributed Systems 8-10 Years (Tech Lead) Hard Production Scenario

How does Log Aggregation and Distributed Tracing work with OpenTelemetry, Jaeger, and ELK Stack?

Incident Scenario: A user checkout request spans 6 microservices and 14 database queries. How do you trace where the latency occurred using a unified `trace_id`?
59 views • Direct Permalink

Distributed Context Propagation

  1. The edge API gateway generates a unique trace_id and span_id.
  2. Passed downstream across all HTTP/gRPC headers via W3C Trace Context (traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01).
  3. Each microservice logs the trace_id and exports span metrics to OpenTelemetry collector / Jaeger for visual timeline waterfalls.
Tags: #Distributed Tracing #OpenTelemetry #Jaeger #Observability
Laravel Advanced & Architecture 8-10 Years (Tech Lead) Hard Production Scenario

Explain the internal architecture of Laravel Broadcast Channels, Pusher, and Laravel Reverb WebSockets.

Incident Scenario: Scaling live chat and notifications to 100,000 concurrent socket connections without dropping messages or overwhelming backend servers.
691 views • Direct Permalink

Laravel Reverb Architecture

Laravel Reverb is a first-party, high-performance WebSocket server written directly in PHP using asynchronous event loops.

  • Epoll Event Loop: Capable of sustaining tens of thousands of open TCP sockets on a single server.
  • Horizontal Scaling via Redis Pub/Sub: When server A broadcasts an event, it publishes to Redis; Server B, C, and D receive the pub/sub notification and relay the frame to their local connected client sockets.
  • Zero Third-Party Billing: Direct drop-in replacement for Pusher.
Tags: #Reverb #WebSockets #Broadcasting #Realtime #Pusher
Modern PHP 8.x & Internals 10+ Years (Principal / Architect) Hard Production Scenario

How do you design a High-Performance In-Memory Cache using Shared Memory (`shmop` / APCu) in PHP without Redis?

Incident Scenario: A microservice running on a single bare-metal server needs to read configuration maps in sub-0.1ms without network socket overhead.
452 views • Direct Permalink

APCu Direct RAM Access

APCu stores PHP variables directly in the web server process shared memory, avoiding TCP network roundtrips to Redis:

if (! apcu_exists('global_config')) {
    $config = loadHeavyConfig();
    apcu_store('global_config', $config, 3600);
} else {
    $config = apcu_fetch('global_config');
}

Latency is under 5 microseconds, compared to 0.5-2ms for Redis over TCP.

Tags: #APCu #Shared Memory #Low Latency #Cache
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Hard Production Scenario

How do you optimize Foreign Key checks and cascading deletes on huge tables without causing lock contention?

Incident Scenario: Deleting a customer record triggered `ON DELETE CASCADE` on 200,000 child records, freezing the database.
656 views • Direct Permalink

Best Practice for High-Scale Systems

Avoid heavy database-level cascading deletes. Instead, perform soft-deletes or chunked background queue deletions:

-- Delete in chunks of 5,000 to prevent long-held row locks
DELETE FROM order_items WHERE order_id = 12345 LIMIT 5000;
Tags: #Foreign Keys #Cascading Delete #Locking
PostgreSQL Enterprise & Performance 10+ Years (Principal / Architect) Expert Production Scenario

How do you tune `shared_buffers`, `work_mem`, and `maintenance_work_mem` for optimal PostgreSQL performance?

Incident Scenario: Configuring a new 64-core, 256GB RAM database server for heavy OLTP workloads.
417 views • Direct Permalink

Optimal Memory Configuration

  • shared_buffers: Set to 25% of total RAM (64GB). PostgreSQL relies heavily on the Linux OS Page Cache for the remaining 75%.
  • work_mem: Allocated per-sort/hash operation per client (e.g. 32MB to 64MB). (Formula: (Available RAM / Max Connections) / 3).
  • maintenance_work_mem: Allocated for VACUUM and CREATE INDEX (e.g. 4GB).
  • effective_cache_size: Set to 75% of total RAM (192GB) to inform the optimizer of OS cache capacity.
Tags: #PostgreSQL Tuning #Memory Configuration #DevOps
System Design, Redis & Distributed Systems 10+ Years (Principal / Architect) Expert Production Scenario

How do you secure Microservices using Mutual TLS (mTLS) and OAuth2 Token Exchange in a Zero-Trust architecture?

Incident Scenario: Preventing lateral movement and man-in-the-middle packet sniffing inside a Kubernetes cluster if an internal container is compromised.
439 views • Direct Permalink

Mutual TLS (mTLS) with Service Mesh (Istio / Linkerd)

  • Both client and server authenticate each other using X.509 cryptographic certificates rotated automatically by the service mesh control plane.
  • All internal pod-to-pod network traffic is encrypted with TLS 1.3.
  • Combined with short-lived JWT scoped tokens to verify service-level authorization.
Tags: #mTLS #Zero Trust #Service Mesh #Security #OAuth2
Laravel Advanced & Architecture 10+ Years (Principal / Architect) Expert Production Scenario

How do you design a robust Event-Sourced audit trail with CQRS in Laravel without third-party monolith packages?

Incident Scenario: A healthcare management system requires immutable historical state recreation so auditors can view the exact state of a medical record at any millisecond in the past 5 years.
363 views • Direct Permalink

Event Sourcing Core Principles

  1. Append-Only Event Store: State changes are stored as immutable past-tense events (PatientDiagnosed, PrescriptionIssued). The database table has NO UPDATE or DELETE permissions.
  2. Replaying State:
    $record = new MedicalRecord();
    foreach ($eventStream as $event) {
        $record->apply($event);
    }
    
  3. Projections (Read Models): Asynchronous queue listeners consume domain events and project denormalized read-optimized views into Elasticsearch or Postgres for fast querying.
Tags: #Event Sourcing #CQRS #Audit Trail #Immutability #Healthcare
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium

Explain Late Static Binding (`static::` vs `self::`) in complex class inheritance hierarchies.

Incident Scenario: A base ActiveRecord model factory was returning instances of the parent class instead of the derived subclass.
256 views • Direct Permalink

Late Static Binding

  • self:: resolves to the class where the method is written.
  • static:: resolves to the class that was actually called at runtime.
class Model {
    public static function create(): static {
        return new static(); // Returns instance of User when called as User::create()
    }
}

class User extends Model {}

$user = User::create(); // Instance of User
Tags: #Late Static Binding #OOP #Inheritance #Design Patterns
MySQL Tuning, Indexing & Concurrency 8-10 Years (Tech Lead) Hard

What is the purpose of the MySQL Redo Log and Undo Log in Crash Recovery?

Incident Scenario: The server suffered an abrupt power failure during heavy transaction processing. How does MySQL restore consistency upon restart?
422 views • Direct Permalink

Redo Log vs Undo Log

  • Redo Log (Write-Ahead Logging / WAL): Records physical changes to data pages. During crash recovery, MySQL replays the redo log to restore committed transactions that were not yet flushed from RAM to table data files.
  • Undo Log: Records the opposite actions needed to rollback uncommitted transactions active at the time of the crash.
Tags: #Redo Log #Undo Log #Crash Recovery #WAL
System Design, Redis & Distributed Systems 5-8 Years (Senior) Medium Production Scenario

How do you design a High-Throughput Leaderboard System with Millions of Scores using Redis Sorted Sets (`ZSET`)?

Incident Scenario: Real-time gaming platform tracking top 100 player ranks out of 10 million players updating scores continuously.
328 views • Direct Permalink

Redis Sorted Sets ($O(\log N)$ Complexity)

# Add / update player score
ZADD leaderboard 4500 "user_9821"

# Get user current global rank (0-indexed)
ZREVRANK leaderboard "user_9821"

# Fetch top 10 players with scores
ZREVRANGE leaderboard 0 9 WITHSCORES

Internal SkipList data structure delivers sub-millisecond lookups across millions of elements.

Tags: #Redis ZSET #Leaderboard #SkipList #Performance
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How does Laravel Sanctum issue and validate SPA cookies vs Mobile Personal Access Tokens?

Incident Scenario: A developer configured Sanctum for a Vue.js SPA and an iOS app, but the SPA kept receiving 419 CSRF Token Mismatch errors in cross-domain staging environments.
642 views • Direct Permalink

Sanctum Dual-Mode Authentication

  1. SPA (Cookie-Based Stateful Auth):
    • Client calls GET /sanctum/csrf-cookie to set XSRF-TOKEN cookie.
    • Client includes X-XSRF-TOKEN header and withCredentials: true.
    • Domain must match SANCTUM_STATEFUL_DOMAINS in .env.
  2. Mobile Apps (Bearer Tokens):
    • Issue token via $user->createToken('iphone')->plainTextToken.
    • Stored in hashed format in personal_access_tokens table.
    • Included as Authorization: Bearer <token> header without CSRF requirements.
Tags: #Sanctum #Authentication #SPA #CORS #CSRF #Security