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 configure and optimize Laravel for High-Concurrency Microservices using gRPC and HTTP/2?
gRPC with Protocol Buffers in PHP
- Binary Serialization vs JSON: Protocol Buffers serialize payloads into compact binary format, reducing payload size by 70% and CPU deserialization time by 80%.
- HTTP/2 Multiplexing: Multiple bidirectional gRPC RPC calls share a single persistent TCP connection, preventing ephemeral port exhaustion.
- RoadRunner gRPC Plugin: Run Laravel worker processes through Spiral RoadRunner gRPC server for native C-level gRPC transport.
How do Enums in PHP 8.1+ support Backed Values, Methods, and Interfaces?
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);
}
}
How do Generated (Virtual & Stored) Columns and Functional Indexes optimize queries in MySQL 8?
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.
How do you perform Zero-Downtime Index Creation in PostgreSQL using `CONCURRENTLY`?
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/DELETEoperations. - Note: Cannot run inside a multi-statement transaction block.
How do you design a Resilient Multi-Region Disaster Recovery architecture (Active-Active vs Active-Passive)?
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.
How do you handle Dynamic Database Connection Routing (Read/Write Splitting) and Replica Lag in Laravel?
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);
How do you implement and verify Cryptographic Signatures (HMAC-SHA256) with timing attack prevention in PHP?
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.");
}
How does `innodb_flush_log_at_trx_commit` trade ACID durability for 10x write throughput?
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.
Explain CTE Optimization Fencing (`AS MATERIALIZED` vs `AS NOT MATERIALIZED`) in PostgreSQL 12+.
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.
How does Log Aggregation and Distributed Tracing work with OpenTelemetry, Jaeger, and ELK Stack?
Distributed Context Propagation
- The edge API gateway generates a unique
trace_idandspan_id. - Passed downstream across all HTTP/gRPC headers via W3C Trace Context (
traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01). - Each microservice logs the
trace_idand exports span metrics to OpenTelemetry collector / Jaeger for visual timeline waterfalls.
Explain the internal architecture of Laravel Broadcast Channels, Pusher, and Laravel Reverb WebSockets.
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.
How do you design a High-Performance In-Memory Cache using Shared Memory (`shmop` / APCu) in PHP without Redis?
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.
How do you optimize Foreign Key checks and cascading deletes on huge tables without causing lock contention?
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;
How do you tune `shared_buffers`, `work_mem`, and `maintenance_work_mem` for optimal PostgreSQL performance?
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.32MBto64MB). (Formula:(Available RAM / Max Connections) / 3).maintenance_work_mem: Allocated forVACUUMandCREATE INDEX(e.g.4GB).effective_cache_size: Set to 75% of total RAM (192GB) to inform the optimizer of OS cache capacity.
How do you secure Microservices using Mutual TLS (mTLS) and OAuth2 Token Exchange in a Zero-Trust architecture?
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.
How do you design a robust Event-Sourced audit trail with CQRS in Laravel without third-party monolith packages?
Event Sourcing Core Principles
- Append-Only Event Store: State changes are stored as immutable past-tense events (
PatientDiagnosed,PrescriptionIssued). The database table has NOUPDATEorDELETEpermissions. - Replaying State:
$record = new MedicalRecord(); foreach ($eventStream as $event) { $record->apply($event); } - Projections (Read Models): Asynchronous queue listeners consume domain events and project denormalized read-optimized views into Elasticsearch or Postgres for fast querying.
Explain Late Static Binding (`static::` vs `self::`) in complex class inheritance hierarchies.
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
What is the purpose of the MySQL Redo Log and Undo Log in Crash Recovery?
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.
How do you design a High-Throughput Leaderboard System with Millions of Scores using Redis Sorted Sets (`ZSET`)?
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.
How does Laravel Sanctum issue and validate SPA cookies vs Mobile Personal Access Tokens?
Sanctum Dual-Mode Authentication
- SPA (Cookie-Based Stateful Auth):
- Client calls
GET /sanctum/csrf-cookieto setXSRF-TOKENcookie. - Client includes
X-XSRF-TOKENheader andwithCredentials: true. - Domain must match
SANCTUM_STATEFUL_DOMAINSin.env.
- Client calls
- Mobile Apps (Bearer Tokens):
- Issue token via
$user->createToken('iphone')->plainTextToken. - Stored in hashed format in
personal_access_tokenstable. - Included as
Authorization: Bearer <token>header without CSRF requirements.
- Issue token via