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 Unhandled Exceptions and Fatal Errors gracefully in PHP 8 with custom error handlers?
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;
});
How does MySQL 8 CTE (Common Table Expressions) and Recursive Queries simplify hierarchical data traversal?
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;
How does Database Connection Starvation happen during traffic spikes and how do you configure Maximum Connection limits?
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.
How do you optimize Laravel Eloquent Subqueries and Window Functions for enterprise analytics dashboards?
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.
Explain the differences between Deep Copy vs Shallow Copy with PHP `clone` and `__clone()`.
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;
}
}
How do you optimize `LIKE "%search%"` full string searches on tables with millions of rows without elasticsearch?
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);
Explain Write-Through vs. Write-Behind (Write-Back) vs. Cache-Aside caching strategies.
Caching Strategies
- Cache-Aside (Lazy Loading): Application reads cache; on miss, reads DB and writes to cache. Standard for most web apps.
- Write-Through: Application writes to cache, and cache synchronously writes to DB before returning. Consistency guaranteed, higher write latency.
- 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.
How do you securely implement dynamic custom validation rules in Laravel that query external Microservice APIs?
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());
}
}
}
How do you optimize PHP-FPM `pm = dynamic` vs `pm = static` for high-concurrency servers?
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
How do you safely rename a column or drop an index in MySQL production without taking locks?
MySQL 8 Invisible Indexes & Online Drop
- Make Index Invisible First:
Verifies if optimizer or queries degrade without that index.ALTER TABLE orders ALTER INDEX idx_old_status INVISIBLE; - Drop Online:
ALTER TABLE orders DROP INDEX idx_old_status, ALGORITHM=INPLACE, LOCK=NONE;
How do you design a Secure Content Delivery Network (CDN) Token Authentication system for private video streaming?
HMAC-Signed URLs with Expiration & IP Binding
- Backend generates an HMAC-signed URL containing:
path,expires_timestamp, and optionalclient_ip. - 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 - If token expired or tampered, edge rejects with HTTP 403 without touching origin servers.
How do you implement Dynamic Multi-Factor Authentication (MFA/TOTP) with backup recovery codes in Laravel 11/12/13?
TOTP Implementation Workflow
- Secret Generation: Generate 32-character base32 secret and store encrypted in database (
Crypt::encryptString($secret)). - QR Code Provisioning: Generate
otpauth://totp/App:user@email?secret=...&issuer=App. - Verification: Validate code within drift window (+/- 30 seconds).
- Hashed Recovery Codes: Generate 8 random recovery codes, hash them with
Hash::make()before saving, and burn upon single use.
How do Readonly Classes in PHP 8.2+ enforce immutability in Domain-Driven Design (DDD) Data Transfer Objects (DTOs)?
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
) {}
}
How does Group Replication and MySQL InnoDB Cluster achieve High Availability (HA) with zero data loss?
MySQL InnoDB Cluster Architecture
- Group Replication: Uses a Paxos-based consensus protocol where transactions are validated across majority nodes (quorum) before commit.
- MySQL Router: Automatically routes incoming read/write traffic to the primary node and read traffic across secondaries.
- Automatic Failover: If the primary crashes, the cluster elects a new primary in seconds without human intervention.
How do you design a Scalable Full-Text Search Engine with Elasticsearch / Meilisearch synchronizing with relational databases?
Change Data Capture (CDC) via Debezium & Kafka
Instead of dual-writing in application code (which risks desynchronization if search fails):
- Database writes to transaction WAL (Binlog).
- Debezium CDC connector tails the Binlog and streams row change events to Kafka.
- An indexing consumer batch writes updates into Elasticsearch / Meilisearch. Guarantees 100% data consistency with sub-second synchronization latency.
How do you manage Database Transactions with external 3rd-party webhook triggers safely in Laravel?
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);
});
});
How do you implement Custom Eloquent Casts with Value Objects in modern Laravel?
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];
}
}
How do you monitor and handle Slow Query alerts in real-time in Laravel production?
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
});
How do you architect Rate Limiting tiers (e.g. Free, Pro, Enterprise) dynamically in Laravel Routing?
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),
};
});
How do you handle graceful worker restarts in Kubernetes / Docker for Laravel Queues and Octane?
Graceful Termination Workflow
- Catch
SIGTERMin worker: In Kubernetes, setterminationGracePeriodSeconds: 120. - Supervisor Configuration: Set
stopwaitsecs = 120so Supervisor gives workers up to 2 minutes to finish processing current job before force killing (SIGKILL). - Queue Worker Command:
php artisan queue:work --stop-when-empty --max-time=3600 --timeout=90