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

•
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How do you handle Unhandled Exceptions and Fatal Errors gracefully in PHP 8 with custom error handlers?

Incident Scenario: Ensuring any unhandled fatal exception renders a clean JSON payload to API clients and reports stack traces to Sentry without printing raw PHP traces.
110 views • Direct Permalink

Handling \Throwable (Exception + Error)

In PHP 7+, all exceptions and fatal runtime errors implement \Throwable:

set_exception_handler(function (\Throwable $e) {
    Log::error($e->getMessage(), ['trace' => $e->getTraceAsString()]);

    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'error' => 'Internal Server Error',
        'code' => 500,
    ]);
    exit;
});
Tags: #Error Handling #Exceptions #Throwable #Sentry
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Medium Production Scenario

How does MySQL 8 CTE (Common Table Expressions) and Recursive Queries simplify hierarchical data traversal?

Incident Scenario: Querying an organization tree of managers, subordinates, and department hierarchies.
696 views • Direct Permalink

Recursive CTE Example

WITH RECURSIVE OrgChart AS (
    SELECT id, name, manager_id, 1 as level
    FROM employees WHERE manager_id IS NULL
    UNION ALL
    SELECT e.id, e.name, e.manager_id, o.level + 1
    FROM employees e
    JOIN OrgChart o ON e.manager_id = o.id
)
SELECT * FROM OrgChart ORDER BY level;
Tags: #CTE #Recursive Queries #MySQL 8 #Hierarchical Data
System Design, Redis & Distributed Systems 8-10 Years (Tech Lead) Hard Production Scenario

How does Database Connection Starvation happen during traffic spikes and how do you configure Maximum Connection limits?

Incident Scenario: During a marketing campaign, 400 auto-scaled web workers each opened 20 database connections, crashing MySQL with `Too many connections` (max 1,000).
645 views • Direct Permalink

Connection Pooling with ProxySQL / PgBouncer

  • Without connection pooling: $400 \text{ pods} \times 20 \text{ connections} = 8,000 \text{ open DB connections}$, overwhelming database thread management.
  • With Multiplexing Proxy: 8,000 application client connections multiplex over 50 persistent, high-speed connections to MySQL, keeping DB CPU in the sweet spot.
Tags: #Connection Pooling #Database Starvation #Auto Scaling #ProxySQL
Laravel Advanced & Architecture 5-8 Years (Senior) Hard Production Scenario

How do you optimize Laravel Eloquent Subqueries and Window Functions for enterprise analytics dashboards?

Incident Scenario: Generating a monthly leaderboard ranking top 100 students by quiz completion speed and course score required grouping across 2 million rows.
452 views • Direct Permalink

Utilizing selectSub and addSelect with Window Functions

$rankedStudents = User::query()
    ->select('id', 'name', 'email')
    ->addSelect([
        'last_quiz_score' => QuizAttempt::select('score')
            ->whereColumn('user_id', 'users.id')
            ->latest('completed_at')
            ->limit(1),
        'rank' => DB::table('quiz_attempts')
            ->selectRaw('DENSE_RANK() OVER (ORDER BY SUM(score) DESC)')
            ->whereColumn('user_id', 'users.id')
    ])
    ->orderByDesc('rank')
    ->take(100)
    ->get();

Avoids loading intermediate Eloquent collections in memory.

Tags: #Eloquent #Subqueries #Window Functions #Analytics #SQL
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

Explain the differences between Deep Copy vs Shallow Copy with PHP `clone` and `__clone()`.

Incident Scenario: Cloning an Invoice object also modified the customer profile of the original invoice because nested objects were copied by reference.
257 views • Direct Permalink

Shallow vs Deep Clone

Standard $b = clone $a copies primitive properties by value, but nested objects remain references to the original instance.

class Invoice
{
    public Customer $customer;

    public function __clone()
    {
        // Deep copy nested object
        $this->customer = clone $this->customer;
    }
}
Tags: #Cloning #OOP #Memory #Deep Copy
MySQL Tuning, Indexing & Concurrency 5-8 Years (Senior) Medium Production Scenario

How do you optimize `LIKE "%search%"` full string searches on tables with millions of rows without elasticsearch?

Incident Scenario: Product title searches with leading wildcards (`LIKE "%laptop%"`) could not use regular B+Tree indexes.
60 views • Direct Permalink

MySQL FULLTEXT Index with N-Gram Parser

ALTER TABLE products ADD FULLTEXT INDEX ft_title_desc (title, description) WITH PARSER ngram;

-- High performance full text search
SELECT * FROM products
WHERE MATCH(title, description) AGAINST('+laptop +pro' IN BOOLEAN MODE);
Tags: #Fulltext Index #LIKE Search #Performance
System Design, Redis & Distributed Systems 5-8 Years (Senior) Medium

Explain Write-Through vs. Write-Behind (Write-Back) vs. Cache-Aside caching strategies.

Incident Scenario: Choosing caching architectures for high-frequency GPS tracking ingestion vs low-frequency user profile settings.
678 views • Direct Permalink

Caching Strategies

  1. Cache-Aside (Lazy Loading): Application reads cache; on miss, reads DB and writes to cache. Standard for most web apps.
  2. Write-Through: Application writes to cache, and cache synchronously writes to DB before returning. Consistency guaranteed, higher write latency.
  3. Write-Back (Write-Behind): Application writes to cache immediately; cache asynchronously flushes batch writes to DB in the background. High write performance, small risk of data loss if cache crashes before sync.
Tags: #Cache Aside #Write Through #Write Back #Architecture
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How do you securely implement dynamic custom validation rules in Laravel that query external Microservice APIs?

Incident Scenario: Validating VAT numbers and enterprise business tax IDs against European VIES SOAP/REST APIs during user registration without hanging requests if the external service is slow.
647 views • Direct Permalink

Implementing Invokable Rule with Circuit Breaker & Timeout

class ValidEnterpriseTaxNumber implements ValidationRule
{
    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        try {
            $response = Http::timeout(2)
                ->retry(2, 100)
                ->get("https://api.taxservice.com/validate/{$value}");

            if (! $response->successful() || ! $response->json('is_valid')) {
                $fail("The {$attribute} is not a verified business tax entity.");
            }
        } catch (\Throwable $e) {
            // Log warning and fail gracefully or flag for manual review
            Log::warning("Tax API unavailable: " . $e->getMessage());
        }
    }
}
Tags: #Validation #Custom Rules #External APIs #Timeouts #Resilience
Modern PHP 8.x & Internals 8-10 Years (Tech Lead) Hard Production Scenario

How do you optimize PHP-FPM `pm = dynamic` vs `pm = static` for high-concurrency servers?

Incident Scenario: A server with 64GB RAM and 32 vCPU crashed during traffic surges with `server reached pm.max_children setting` errors.
668 views • Direct Permalink

Calculating Optimal pm = static Configuration

On dedicated production servers, pm = static avoids the CPU overhead of constantly spawning and destroying worker processes.

Formula:

max_children = (Total RAM - OS/Services RAM) / Average Worker Memory (e.g. 50MB)
Example: (60,000 MB) / 50 MB = 1200 workers
pm = static
pm.max_children = 1200
pm.max_requests = 1000 ; Recycles workers to prevent slow memory leaks
Tags: #PHP-FPM #Server Tuning #DevOps #Concurrency #High Traffic
MySQL Tuning, Indexing & Concurrency 8-10 Years (Tech Lead) Medium Production Scenario

How do you safely rename a column or drop an index in MySQL production without taking locks?

Incident Scenario: Dropping an unused index on a busy 80M row table caused application write queries to stall.
276 views • Direct Permalink

MySQL 8 Invisible Indexes & Online Drop

  1. Make Index Invisible First:
    ALTER TABLE orders ALTER INDEX idx_old_status INVISIBLE;
    
    Verifies if optimizer or queries degrade without that index.
  2. Drop Online:
    ALTER TABLE orders DROP INDEX idx_old_status, ALGORITHM=INPLACE, LOCK=NONE;
    
Tags: #Online DDL #Index Management #Production Safety
System Design, Redis & Distributed Systems 5-8 Years (Senior) Medium Production Scenario

How do you design a Secure Content Delivery Network (CDN) Token Authentication system for private video streaming?

Incident Scenario: Ensuring paid video course URLs cannot be shared on social media or hotlinked by unauthorized users.
656 views • Direct Permalink

HMAC-Signed URLs with Expiration & IP Binding

  1. Backend generates an HMAC-signed URL containing: path, expires_timestamp, and optional client_ip.
  2. Cloudflare / CloudFront edge worker validates the signature in $O(1)$ at the edge node:
    https://cdn.example.com/video/master.m3u8?token=a8f9c1...&exp=1772189400
    
  3. If token expired or tampered, edge rejects with HTTP 403 without touching origin servers.
Tags: #CDN #Signed URLs #Security #Streaming
Laravel Advanced & Architecture 8-10 Years (Tech Lead) Hard Production Scenario

How do you implement Dynamic Multi-Factor Authentication (MFA/TOTP) with backup recovery codes in Laravel 11/12/13?

Incident Scenario: Enterprise compliance SOC2 demands time-based one-time password (TOTP RFC 6238) support with cryptographically secure single-use recovery codes.
712 views • Direct Permalink

TOTP Implementation Workflow

  1. Secret Generation: Generate 32-character base32 secret and store encrypted in database (Crypt::encryptString($secret)).
  2. QR Code Provisioning: Generate otpauth://totp/App:user@email?secret=...&issuer=App.
  3. Verification: Validate code within drift window (+/- 30 seconds).
  4. Hashed Recovery Codes: Generate 8 random recovery codes, hash them with Hash::make() before saving, and burn upon single use.
Tags: #Security #MFA #TOTP #Cryptography #SOC2
Modern PHP 8.x & Internals 5-8 Years (Senior) Medium Production Scenario

How do Readonly Classes in PHP 8.2+ enforce immutability in Domain-Driven Design (DDD) Data Transfer Objects (DTOs)?

Incident Scenario: Designing an immutable Value Object for financial ledger entries that prevents any property mutations once instantiated.
599 views • Direct Permalink

PHP 8.2 Readonly Classes

Marking a class readonly automatically enforces that all declared properties are readonly and prevents dynamic property creation:

readonly class TransferLedgerDTO
{
    public function __construct(
        public string $transactionId,
        public int $amountCents,
        public string $currency,
        public DateTimeImmutable $timestamp
    ) {}
}
Tags: #Readonly Classes #DDD #Immutability #PHP 8.2
MySQL Tuning, Indexing & Concurrency 10+ Years (Principal / Architect) Expert Production Scenario

How does Group Replication and MySQL InnoDB Cluster achieve High Availability (HA) with zero data loss?

Incident Scenario: Architecting an automated database failover system across 3 availability zones with Paxos consensus.
575 views • Direct Permalink

MySQL InnoDB Cluster Architecture

  1. Group Replication: Uses a Paxos-based consensus protocol where transactions are validated across majority nodes (quorum) before commit.
  2. MySQL Router: Automatically routes incoming read/write traffic to the primary node and read traffic across secondaries.
  3. Automatic Failover: If the primary crashes, the cluster elects a new primary in seconds without human intervention.
Tags: #InnoDB Cluster #Group Replication #High Availability #Paxos
System Design, Redis & Distributed Systems 8-10 Years (Tech Lead) Hard Production Scenario

How do you design a Scalable Full-Text Search Engine with Elasticsearch / Meilisearch synchronizing with relational databases?

Incident Scenario: Ensuring search indexes reflect real-time database updates within 1 second without double-writing failures.
488 views • Direct Permalink

Change Data Capture (CDC) via Debezium & Kafka

Instead of dual-writing in application code (which risks desynchronization if search fails):

  1. Database writes to transaction WAL (Binlog).
  2. Debezium CDC connector tails the Binlog and streams row change events to Kafka.
  3. An indexing consumer batch writes updates into Elasticsearch / Meilisearch. Guarantees 100% data consistency with sub-second synchronization latency.
Tags: #Elasticsearch #Meilisearch #Change Data Capture #Debezium #Search
Laravel Advanced & Architecture 5-8 Years (Senior) Hard Production Scenario

How do you manage Database Transactions with external 3rd-party webhook triggers safely in Laravel?

Incident Scenario: A transaction was committed, but an unhandled exception in an external Stripe webhook inside the transaction closure rolled back the database after Stripe had already charged the credit card.
374 views • Direct Permalink

The Golden Rule: Never call external network APIs inside a database transaction

Use DB::afterCommit() callbacks:

DB::transaction(function () use ($order, $paymentData) {
    $order->update(['status' => 'paid']);
    PaymentTransaction::create([...]);

    // Dispatch side-effects ONLY after database commit succeeds
    DB::afterCommit(function () use ($order) {
        SendInvoiceEmailJob::dispatch($order);
        NotifyThirdPartyFulfillment::dispatch($order);
    });
});
Tags: #Database Transactions #Webhooks #Stripe #Consistency
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How do you implement Custom Eloquent Casts with Value Objects in modern Laravel?

Incident Scenario: A fintech app handles multi-currency amounts (USD, EUR, JPY) and needs to avoid floating point precision errors by casting database integers to immutable `Money` Value Objects.
345 views • Direct Permalink

Implementing CastsAttributes

class MoneyCast implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): ?Money
    {
        return $value !== null ? new Money((int) $value, $attributes['currency'] ?? 'USD') : null;
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): array
    {
        if ($value instanceof Money) {
            return [$key => $value->getAmountInCents(), 'currency' => $value->getCurrency()];
        }
        return [$key => (int) $value];
    }
}
Tags: #Eloquent #Custom Casts #Value Objects #DDD #Fintech
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How do you monitor and handle Slow Query alerts in real-time in Laravel production?

Incident Scenario: You need an automated Slack/Sentry alert whenever any database query takes longer than 500ms in production.
286 views • Direct Permalink

Using DB::whenQueryingForLongerThan

In AppServiceProvider::boot():

DB::whenQueryingForLongerThan(500, function (Connection $connection) {
    Log::warning("Database query exceeded 500ms on [{$connection->getName()}]");
    // Send alert to Sentry or Slack webhook
});
Tags: #Monitoring #Database #Performance #DB Listeners
Laravel Advanced & Architecture 5-8 Years (Senior) Medium Production Scenario

How do you architect Rate Limiting tiers (e.g. Free, Pro, Enterprise) dynamically in Laravel Routing?

Incident Scenario: An enterprise developer API needs tiered rate limits: Free (60 req/min), Pro (1,000 req/min), Enterprise (10,000 req/min) based on the user's active subscription plan.
678 views • Direct Permalink

Dynamic Rate Limiter in AppServiceProvider

RateLimiter::for('api', function (Request $request) {
    $user = $request->user();
    if (! $user) {
        return Limit::perMinute(30)->by($request->ip());
    }

    return match ($user->subscription_tier) {
        'enterprise' => Limit::perMinute(10000)->by($user->id),
        'pro' => Limit::perMinute(1000)->by($user->id),
        default => Limit::perMinute(60)->by($user->id),
    };
});
Tags: #Rate Limiting #Routing #Security #SaaS
Laravel Advanced & Architecture 8-10 Years (Tech Lead) Hard Production Scenario

How do you handle graceful worker restarts in Kubernetes / Docker for Laravel Queues and Octane?

Incident Scenario: During Kubernetes rolling deployments, pods received `SIGTERM` and immediately died, terminating active payment processing jobs mid-flight and corrupting order status.
94 views • Direct Permalink

Graceful Termination Workflow

  1. Catch SIGTERM in worker: In Kubernetes, set terminationGracePeriodSeconds: 120.
  2. Supervisor Configuration: Set stopwaitsecs = 120 so Supervisor gives workers up to 2 minutes to finish processing current job before force killing (SIGKILL).
  3. Queue Worker Command:
    php artisan queue:work --stop-when-empty --max-time=3600 --timeout=90
    
Tags: #Kubernetes #Docker #Graceful Shutdown #SIGTERM #DevOps