7 Meta Php Developer Interview Questions & Answers

meta icon

Questions with Detailed ExplanationsWith Detailed Explanations

(Last Updated: August 28, 2026)

1. Find the k closest integers to x in a sorted array.CodingMediumMeta

Question Details

Given a sorted integer array arr and integers k and x, return the k integers closest to x, with the result sorted in ascending order.

Short Interview Answer (30-60 seconds)

I would first use binary search to find the split point around x, then I grow a window from both sides until it contains k numbers. At each step I compare the distances on the left and right, and I drop the side that is farther from x. When the distances are equal, I keep the left side, which matches the diagram. Because the array is sorted, the final slice is already in ascending order. This runs in O(log n + k) time and O(1) extra space.

Detailed Explanation

See the Code while reading this explanation.

We are given a sorted array, and we need the k values closest to x. The output must stay in ascending order, so we do not sort again. The clean approach is to first find where x fits in the sorted list, then grow a window around that point. Because the array is sorted, the two sides around x are easy to compare one step at a time. That keeps the logic simple and makes the final slice easy to return.

Useful Questions to Ask the Interviewer
  1. Is the array always sorted in ascending order?
  2. If two values are equally close to x, should I keep the smaller one?
  3. Can k be equal to the full array length?
Find the k closest integers to x in a sorted array. diagram
How to Explain It in an Interview
1. Understand the input and required output

The input is a sorted integer array arr, plus the integers k and x. The output is the k integers closest to x, in ascending order. The diagram uses arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], k = 4, and x = 5. The answer shown is [3, 4, 5, 6].

2. Choose the algorithm and data structure

I use binary search first. It finds the first index whose value is at least x. Then I use two moving indexes as a window. The invariant is simple. The current window always contains the best values chosen so far, and each move removes the side that is farther from x.

3. Initialize the state

I start with left = 0 and right = n. After binary search finishes, left becomes the last index smaller than x, and right becomes the first index that is at least x. Then I set the initial window around that split point.

4. Walk through the example

For arr = [1, 2, 3, 4, 5, 6, 7, 8, 9], k = 4, and x = 5, binary search finds right = 4 because arr[4] = 5. Then left = 3 and right = 4, so the initial window is [4, 5].

Step 1: Compare 5 - arr[left] = 5 - 4 = 1 with arr[right] - 5 = 5 - 5 = 0. The right side is closer, so right moves to 5. Step 2: Compare 5 - 4 = 1 with 6 - 5 = 1. The left side is closer or equal, so left moves to 2. Step 3: The window now has size 4. It is [3, 4, 5, 6]. The process stops.

5. Explain why the result is correct

The window always keeps the closest values around x. When the left value is farther, we remove it. When the right value is farther, we remove it. When the distances are equal, the diagram keeps the left side, which means the smaller value stays in the final answer. When the window reaches size k, every value outside the window is worse than a value inside it, so the remaining slice is the answer.

6. Explain the PHP implementation

The code first counts the array length. Then it runs binary search to find the first position with value at least x. After that, it grows the window until the window size becomes k. If the left side is outside the array, the code moves right. If the right side is outside the array, the code moves left. Otherwise it compares the two edge distances and removes the farther side. At the end, array_slice returns the k values from left + 1. The values stay sorted because the original array was sorted.

7. Explain complexity and edge cases

Binary search takes O(log n) time. Expanding the window takes O(k) time. So the total time is O(log n + k). Extra space is O(1) because the code only uses a few index variables. Important edge cases are k = n, x smaller than all values, x larger than all values, and duplicate values. The tie rule in the diagram prefers the left side when the distances are equal.

Key Insight / Why This Solution Works

The key idea is to use the sorted order first. Binary search finds the split point around x very fast. Then the algorithm grows a window from that split point. The window invariant is that it always contains the k closest values chosen so far. At each step, the code compares the left boundary and the right boundary. It removes the side that is farther from x, or the right side only when the left side is clearly worse. When the window reaches size k, the middle slice is the answer, and it is already sorted.

Code
<?php
function findClosestElements(array $arr, int $k, int $x): array {
    $n = count($arr);

    // Step 1: Binary search for the first index with arr[right] >= x
    $left = 0; $right = $n;
    while ($left < $right) {
        $mid = intdiv($left + $right, 2);
        if ($arr[$mid] < $x) {
            $left = $mid + 1;
        } else {
            $right = $mid;
        }
    }

    // left is the first index >= x, so set initial window
    $left = $left - 1; $right = $left + 1;

    // Step 2: Expand window until size becomes k
    while ($right - $left - 1 < $k) {
        if ($left < 0) {
            $right++;
        } elseif ($right >= $n) {
            $left--;
        } elseif ($x - $arr[$left] <= $arr[$right] - $x) {
            $left--;
        } else {
            $right++;
        }
    }

    // Step 3: Collect and return the result
    return array_slice($arr, $left + 1, $k);
}
?>
Time & Space Complexity

Binary search costs O(log n) time. The window expansion costs O(k) time because it moves one side at a time until the window has k values. So the total time is O(log n + k). The extra memory is O(1) because the code only keeps a few indexes and counters. The output slice is not counted as extra space.

Where it is used

This pattern is useful when data is already sorted and we need the values nearest to a target. It can be used in search results, score ranking, time series lookups, and nearest-value queries in ordered lists.

Why Interviewers Ask This

The interviewer wants to see if you can use sorted order well. They also want to see if you can keep a clean window invariant and handle ties and boundaries correctly. They are checking that you can write the PHP loop without off-by-one mistakes and that you can explain the exact time and space cost in simple words.

Common interview mistakes

One common mistake is to compare the wrong neighbors after the binary search split point. Another is to move the wrong side when the distances are equal. In this diagram, ties keep the left side. Some candidates forget the boundary cases when x is smaller than every value or larger than every value. Another mistake is to return indexes instead of the actual values. The answer must be the values in ascending order.

Interview tip

When you explain it, draw the window as two fences around the answer and say that each move removes the side that is farther from x.

Interviewer may ask next
What changes if the array is not sorted?

Then the binary search step no longer works. I would need a different approach, such as sorting first. If I must preserve original positions, I would sort value-index pairs. That changes the time to O(n log n) and uses O(n) extra space for the pairs.

What changes if ties should prefer the larger value instead of the smaller one?

I would change the tie rule so the right side wins when the distances are equal. The rest of the window logic stays the same. The time is still O(log n + k), and the space is still O(1).

2. Find the minimum cost to connect all sticks.CodingMediumMeta

Question Details

Given stick lengths, repeatedly connect two sticks at a cost equal to their combined length and return the minimum total cost required to connect all sticks. Use an efficient priority-queue-based approach.

Short Interview Answer (30-60 seconds)

I would use a min-heap. I put every stick into the heap, then I repeatedly take the two smallest sticks, add their lengths, add that merge cost to the total, and push the new stick back. That greedy order works because the smallest sticks should be combined first to keep future costs low. In PHP, I use SplPriorityQueue with negative priorities to simulate a min-heap. The time is O(n log n), and the extra space is O(n).

Detailed Explanation

See the Code while reading this explanation.

This problem asks us to join many sticks into one stick. Each join costs the sum of the two stick lengths. We want the smallest possible total cost. The diagram shows a greedy method that always joins the two smallest sticks first. That keeps later costs low. The example in the diagram uses [2, 4, 3, 7, 6] and ends at 29.

Useful Questions to Ask the Interviewer
  1. Should I return 0 when there are zero or one sticks?
  2. Can I use PHP's SplPriorityQueue and invert priorities so it behaves like a min-heap?
Find the minimum cost to connect all sticks. diagram
How to Explain It in an Interview
1. Understand the input and required output

The input is a list of stick lengths. The output is one number: the minimum total cost to connect all sticks. We do not return the merge order. We only return the final total.

2. Choose the algorithm and data structure

I use a greedy approach with a min-heap. The heap always keeps the smallest remaining sticks easy to remove. Each round, I remove the two smallest sticks, join them, add the cost, and put the new stick back. That is the core invariant.

3. Initialize the state

I start with total cost = 0. I load every stick into the heap first. In PHP, SplPriorityQueue is a max-priority queue by default, so I store negative priorities. That makes the smallest stick come out first.

4. Walk through the example

For [2, 4, 3, 7, 6], the heap lets me take the two smallest sticks first. The merge sequence shown in the diagram ends with total cost 29. The important idea is the same at every round: remove two smallest, add their sum to the answer, then push the new stick back.

5. Explain why the result is correct

The heap always contains the sticks that are not finished yet. The two smallest ones are the best pair to join next, because using a larger stick too early would make later merges more expensive. Repeating this choice until one stick remains gives the minimum total cost.

6. Explain the PHP implementation

The function takes an array of stick lengths. It creates a SplPriorityQueue and tells it to return only the data. Then it inserts every stick with a negative priority. After that, it keeps extracting two sticks, adding their sum to the running total, and pushing the combined stick back. When one stick is left, it returns the total.

7. Complexity and edge cases

The time is O(n log n). Each insert and extract on the heap takes O(log n), and we do that across all sticks and merge rounds. The extra space is O(n) for the heap. The relevant edge cases are an empty array, one stick, and large stick lengths.

Key Insight / Why This Solution Works

I keep all unfinished sticks in a min-heap. The heap always exposes the two smallest sticks, and I merge those first. That greedy choice is correct because every merge cost is added to the total, so using the smallest pair now keeps later costs as low as possible. After each merge, I push the new stick back into the heap. I repeat this until one stick remains. In PHP, I simulate a min-heap with negative priorities in SplPriorityQueue.

Code
<?php

function connectSticks(array $sticks): int
{
    // SplPriorityQueue is a max-priority queue by default.
    // Use negative priorities so the smallest stick comes out first.
    $heap = new SplPriorityQueue();
    $heap->setExtractFlags(SplPriorityQueue::EXTR_DATA);

    foreach ($sticks as $len) {
        $len = (int) $len;
        $heap->insert($len, -$len);
    }

    $total = 0;

    // Keep merging until only one stick is left.
    while ($heap->count() > 1) {
        $a = $heap->extract();
        $b = $heap->extract();

        $cost = $a + $b;
        $total += $cost;

        // Push the combined stick back into the heap.
        $heap->insert($cost, -$cost);
    }

    return $total;
}

// Example from the diagram
$sticks = [2, 4, 3, 7, 6];
echo connectSticks($sticks) . PHP_EOL; // Output: 29
Time & Space Complexity

The code first loads all sticks into a heap. Then it keeps taking the two smallest sticks and putting the combined stick back. Each heap insert or remove costs O(log n). Across all rounds, the total time is O(n log n). The extra memory is O(n) because the heap can hold all sticks. That matches the diagram.

Where it is used

This pattern is useful when we keep combining the smallest items and every combine has a cost. A common example is Huffman coding. It also shows up in file merge problems, cost aggregation, and other greedy tasks where the next smallest item should be handled first.

Why Interviewers Ask This

Interviewers want to see whether I can spot the greedy pattern and choose the right data structure. They are checking if I know why the two smallest sticks should be merged first, if I can explain the invariant clearly, and if I can use PHP's priority queue correctly. They also want correct complexity analysis and simple edge case handling for empty input and one stick.

Common interview mistakes

A common mistake is using the PHP priority queue as a max-heap and removing the largest sticks first. Another mistake is forgetting to push the merged stick back, which breaks the process. Some candidates stop too early, but the loop must continue until one stick remains. Another mistake is tracking only the last merge cost instead of the running total. It is also wrong to sort once and stop, because every merge creates a new stick that must be handled again.

Interview tip

Say the invariant out loud: the heap always contains the remaining sticks, and each round removes the two smallest ones. That one sentence makes the greedy choice easy to defend.

Interviewer may ask next
How would this change if the language had a real min-heap?

The logic stays the same. I would insert the sticks into the min-heap directly, remove the two smallest sticks each round, add their sum, push it back, and return the same total. The time stays O(n log n) and the space stays O(n). The tradeoff is simpler code because I do not need to invert priorities.

What if I also need the full merge order?

I would store each merged pair in an extra list before pushing the combined stick back. The core algorithm does not change. I still take the two smallest sticks, add their cost, and push the result back. Time stays O(n log n). Space becomes O(n) for the heap plus the output list.

3. Design the Facebook News Feed.System DesignHardMeta

Question Details

Design a scalable Facebook News Feed system. Cover post creation, feed generation, ranking, fan-out strategy, storage, caching, pagination, freshness, high-fan-out users, failure handling, and consistency and latency tradeoffs.

Short Interview Answer (30-60 seconds)

At a high level, this is a read-heavy feed system that must stay fresh and fast. People create posts, but most traffic is users opening the feed and expecting ranked results right away. I would explain the design in three parts: the create path, the feed read path, and the background fan-out work that updates feeds without slowing the user down. The main trade-off is freshness versus latency, because the fastest read path may show slightly old data for a short time.

Detailed Explanation

The goal is to show a person’s home feed in a way that feels fast and useful. The hard part is that many people read the feed all the time, but new posts still have to be stored, ranked, and delivered to the right users. The diagram solves this by splitting the system into a fast read path, a write path for new posts, and background work for fan-out and retries.

Useful Questions to Ask the Interviewer
  1. What does the system need to do? It must accept a new post, keep it safe in storage, and later show a ranked feed for each user. It also has to protect privacy and keep the feed fresh.

2. What questions should I ask first? 1. How fresh must the feed be after a post is created? 2. Which users count as fan-out users?

Design the Facebook News Feed. diagram
How to Explain It in an Interview
1. Explain the goal and the main idea

At a high level, this is a read-heavy feed system. The feed must feel instant, but it also must stay relevant and respect privacy. The top callouts show the main concerns: low latency, horizontal scale, and multi-region support. I would say the system has one fast path for reading and one slower path for background work.

2. Explain the create path

For the create path, the request comes from mobile apps, web, or third-party integrations. It first goes through the edge and API gateway. That layer handles CDN, WAF and DDoS protection, rate limiting, login, permissions, and request validation. Then the PHP application layer accepts the request. The Post Service stores the post and media, and the Social Graph Service applies follow, block, mute, and privacy rules. After the main data is saved, the system sends an event to the message queue so fan-out can happen in the background.

3. Explain the feed read path

For the read path, the client sends a feed request with a cursor and page limit. The Feed Read Service checks cache first, because that is the fastest path. On a cache hit, it can return user feed IDs or metadata quickly. If the cache misses, it falls back to the feed store and the post-related stores. Then the Ranking Service scores posts using recency, affinity, engagement, creator, diversity, and personalization. The result is serialized as JSON and returned to the client.

4. Explain background work and high fan-out handling

The Fan-Out Service consumes queue events in PHP CLI workers. For normal users, it writes home feed entries in the background. For fan-out users, it handles them separately so one celebrity post does not overload the whole system. The Retry or Dead Letter Queue keeps failed jobs from getting lost. The Notification Service also runs in the background for events like new posts, reactions, and comments.

5. Explain scale, failures, and trade-offs

The data side includes the user store, post store, social graph store, feed store, object storage, message queue, cache, and search index. The runtime layer uses PHP 8.4 and 8.5 with PHP-FPM workers for web requests, and PHP CLI workers for queue jobs, plus Opcache and JIT extensions for speed. The design stays fast by using cache and background fan-out, but that means some reads may show older data for a short time. Multi-region deployment improves availability, but it makes consistency harder. Logs, metrics, tracing, alerts, dashboards, and SLOs help the team catch problems early. The main trade-off is simple: faster feeds need more background work and more storage.

Engineering Considerations / Design Trade-offs

The benefit is that normal feed reads can stay fast because the system checks cache first and uses background fan-out for most updates. The downside is that this adds more storage and more moving parts. High fan-out users need special handling, so one popular post does not create too much work at once. Multi-region support improves availability, but it also makes consistency harder. Cache and feed store help with speed, but some users may see slightly older data for a short time. That is a fair trade-off for a news feed.

Why Interviewers Ask This

Interviewers want to see if you can break a big social system into the right flows. They want to know whether you can choose the feed store, cache, queue, and ranking path correctly. They also check if you understand freshness versus latency, privacy checks, and special handling for users with huge reach. Most of all, they want to hear clear judgment, not memorized buzzwords.

Interviewer may ask next
How would you handle a celebrity post with millions of followers?

I would keep the same basic design, but I would treat that user as a special case. The Fan-Out Service should not try to push one post into every follower feed right away. That would create too much work at once. Instead, the post is saved first, and the background workers write only the normal home feed entries that are safe to push quickly. For the very large accounts, I would rely more on read-time assembly, cache, and the feed store so we do not overload the queue. The design stays correct because the post is still saved before fan-out starts, and the feed can still be built from the same source data. I would also keep the ranking step the same so the feed still feels personal. The downside is that some followers may see that post a little later than usual, especially right after it is published.

What would you do if the cache misses for many feed reads?

I would keep the same architecture and make the feed store do more of the work for a short time. On a cache miss, the Feed Read Service already falls back to the feed store and the post-related stores, so the system still works. I would make sure the database write happens first, then cache updates happen after the commit, so we never serve data that was not saved. If misses become common, I would add more cache capacity and tune which feed IDs and hot metadata stay in cache. I would also watch logs and metrics to see whether the problem is a cold cache or a real load spike. The design stays correct because the source data still lives in the main stores. The downside is higher load on storage and a slower feed when the cache is cold.

4. Design an Instagram-style photo and video sharing service with a personalized home feed.System DesignHardMeta

Question Details

Design an Instagram-style service for uploading photos and videos, following users, and generating a personalized home feed. Cover media storage and delivery, metadata, feed generation and ranking, caching, pagination, hot users, moderation, reliability, and scale.

Short Interview Answer (30-60 seconds)

At a high level, this is a media-heavy social system with a very fast read path. People upload photos and videos, follow accounts, and open a personalized feed many times a day. I would break it into three parts: upload and follow changes, feed generation and ranking, and background work like transcoding, moderation, and analytics. The diagram uses PHP-FPM for request handling, MySQL for core data, Redis for fast feed cache, object storage for media, and OpenSearch for search. The main trade-off is speed versus freshness for hot accounts.

Detailed Explanation

This system helps people share photos and videos, follow other users, and see a home feed that feels personal. The hard part is that feed reads must stay fast, while media files and moderation work can happen later. The diagram also shows caching, pagination, hot users, and background jobs. I would explain it in the same order as the diagram: first the upload and follow path, then the feed path, then the background work.

Useful questions to ask are:

Useful Questions to Ask the Interviewer
  1. How fresh should the feed be?
  2. How large are the photos and videos?
  3. How strict should moderation be?
Design an Instagram-style photo and video sharing service with a personalized home feed. diagram
How to Explain It in an Interview
1. Explain the goal and the main idea

At a high level, this is a social app with two jobs. User requests must stay fast, but media work can happen later. The diagram keeps normal HTTP traffic in NGINX and PHP-FPM worker pools, with PHP 8.4 or 8.5 as the runtime. Long-running CLI workers handle background jobs. That split matters because request workers stay light, and heavy video work does not block a feed request.

2. Explain the upload and follow path

For the write path, the request first goes through the API gateway and auth service. The gateway handles TLS termination, request routing, and rate limiting. The auth service handles login, signup, MFA, and token issuance. For media upload, the media service returns a pre-signed URL, so the client uploads directly to object storage. After the upload completes, an event goes to the queue. Media processor workers then transcode video, generate thumbnails, scan for viruses, and run moderation checks. The relationship service updates follows, unfollows, blocks. After the main database write is done, metadata is saved in MySQL.

3. Explain the home feed path

For the read path, the feed service serves the home feed API with cursor-based pagination. On a cache hit, it reads ranked feed data from Redis and returns it quickly. If the cache misses, the ranking service builds a candidate set from follow graph data and other signals, then scores and orders the posts. This is a hybrid fanout design. Normal accounts can fan out on write, but hot users are better handled more on read so one huge account does not flood every follower.

4. Explain background work

The queue keeps slow work away from the main request path. Feed generation workers build timelines and refresh caches. Notification workers send push or in-app messages for likes, comments, follows. Analytics workers export events to the data warehouse. OpenSearch handles search. Cold storage and backup boxes keep archive media and disaster recovery copies. These jobs run in the background, so the feed API does not wait for them.

5. Explain scale, failures, and trade-offs

This design scales by adding more PHP-FPM workers, more queue workers, and more read replicas where needed. Redis helps with hot reads, and MySQL keeps the main data organized. Cursor pagination avoids expensive deep offsets. Observability tracks logs, metrics, traces, and alerts, while security uses encryption in transit and at rest. The main trade-off is freshness versus speed. Cached feeds and fanout keep reads fast, but they can show slightly old data for a short time. Hot-user handling also adds complexity, but it keeps the system stable when one account has many followers.

Engineering Considerations / Design Trade-offs

The benefit is that the service stays fast for the common user actions. CDN and object storage make media delivery cheap and quick. Redis makes feed reads fast, and MySQL keeps the main data organized. The downside is more moving parts. We must keep the cache, queue, and database in sync in a careful way. Fanout on write makes normal feeds quick, but hot users need special handling. Cursor pagination is efficient, but old pages are not random-access friendly. Background processing also means some results, like thumbnails or analytics, may appear a little later.

Why Interviewers Ask This

Interviewers want to see if you can split a hard product into clean flows. They also want to know if you understand the source of truth, the cache, and the background workers. This question checks whether you can protect the main database, keep media handling separate, and explain trade-offs in simple words. It is also a good test of judgment, because hot users, ranking, moderation, and feed freshness all need different choices.

Interviewer may ask next
What if the feed must show new posts within a few seconds for most users?

I would keep the same basic design, but I would push more work into the write path for normal accounts. The feed service would fan out new posts to follower feeds sooner, and the cache would get updated right after the database commit. The ranking service would still handle hot users more on read, so one huge account does not create too much work. This keeps the design correct because MySQL is still the main data store, and Redis is still only a fast layer. The downside is higher write load, more cache churn, and more work whenever many people post at once. We gain fresher feeds, but we pay for it overall with more background and cache traffic later.

What if moderation must block unsafe media before anyone can see it?

I would keep the same upload path, but I would make moderation a required step before the item is marked ready. The client would still upload directly to object storage with a pre-signed URL. Then the media processor workers would transcode, scan, and run moderation rules before the metadata becomes visible in MySQL and before the feed service can use it. That keeps the design correct because unsafe content never reaches the normal read path. The downside is that uploads take longer to appear, and the moderation pipeline becomes a hard gate. The system is safer, but users may wait a little longer after uploading. It also means the queue and workers must stay healthy, or new posts can pile up behind the scan step.

5. Design a messaging service.System DesignHardMeta

Question Details

Design a large-scale messaging service. Cover one-to-one and group messaging, message ordering, delivery and read state, offline users, synchronization across devices, storage, push notifications, retries, abuse controls, and availability and consistency tradeoffs.

Short Interview Answer (30-60 seconds)

At a high level, this is a messaging service for one-to-one and group chat. The hard part is that messages must be saved safely, while online delivery, read state, and device sync must stay fast. I would explain it in three parts: the send path, the real-time and offline delivery path, and the background work plus trade-offs. The diagram uses PHP-FPM for web requests, PHP Ratchet for WebSockets, MySQL as the source of truth, Redis for hot state, and queues for retries and fan-out.

Detailed Explanation

The goal is to let people send chat messages and see them on all devices. The tricky part is that a message may need to reach someone who is offline, while the sender still expects a fast reply. We also need group chat, read receipts, sync, push alerts, and abuse protection. The diagram keeps the fast request path separate from WebSocket delivery and background workers. That lets PHP-FPM handle web requests, while long-running workers handle slow jobs and retries.

Useful Questions to Ask the Interviewer
  1. How many messages per second should we expect?
  2. Do we need message edit, delete, and attachments?
  3. How long should we keep message history and read state?
Design a messaging service. diagram
How to Explain It in an Interview
1. Explain the goal and the main idea

At a high level, this service moves chat messages between people and keeps every device in sync. The hard part is that a message must be saved safely, but delivery should still feel instant. The diagram splits the design into a secure send path, a real-time delivery path, and background work for offline users and retries. The Conversation Service keeps members and chat metadata together, so the rest of the system can use one clear chat identity.

2. Explain the send path

For the send path, the request first goes through the API Gateway and the Auth Service. The diagram shows OAuth2 and JWT here. Then the User Service, Permission Service, Validation & Sanitization, and Rate Limit & Abuse Controls protect the request. After that, the Message Service saves the message in the MySQL Cluster, which is the main source of truth. Once the save succeeds, the service can update Redis for hot state and publish a fan-out event to the Message Queue. The order matters because the data must be safe before background work starts.

3. Explain real-time delivery and offline delivery

For online users, the WebSocket Gateway Cluster sends the message through the real-time path. The Presence Broadcast Service keeps online status, typing, and read receipts moving to subscribed users. The Subscription Manager Service keeps track of user and conversation channels. For offline users, the Delivery Service and Push Service send work into the queue, and workers deliver push notifications through APNs or FCM. If needed, Email or SMS can also be used. Spam / Abuse Protection stays on the side to stop bad traffic. This keeps the main request fast and pushes slow work to the background.

4. Explain sync, read state, and shared data

The Sync Service handles state across devices. It can compare the last sync point and return what changed. The Read Receipt Service tracks read state, and the Attachment Service stores files in S3-compatible object storage. Redis helps with hot data like sessions, profiles, presence, typing, rate limit counters, conversation metadata, and recent read states. MySQL still owns the real data for users, conversations, messages, receipts, and device sessions. That split is important because Redis is only a speed layer.

5. Explain scale, security, observability, and trade-offs

At the end, I would talk about the trade-offs. The system keeps ordering inside a conversation by using sequence IDs. It accepts at-least-once delivery, so the same event may be sent again and needs deduplication. The diagram also shows stateless services, so the system can scale horizontally. Data is partitioned by conversation ID and user ID. Replicas may lag a little, so some reads can be slightly behind. Logs, metrics, tracing, alerting, and dashboards help operators watch the system. The main benefit is speed and availability. The downside is more moving parts and a small delay in some updates.

Engineering Considerations / Design Trade-offs

The main benefit is speed. The send request stays short because heavy work moves to queues and workers. The downside is that some things can arrive a little later, like read state, presence, or push alerts. MySQL keeps the real data safe, while Redis makes common checks faster. The trade-off is that Redis is not the source of truth, so losing it does not lose chat history. The queue also helps retries, but it adds more moving parts. We accept that because messaging systems need to stay up and handle many users at once.

Why Interviewers Ask This

Interviewers want to see whether you can split one hard problem into clear flows. They also want to know if you can keep the main data safe, keep fast delivery separate, and handle offline users without breaking the system. They look for good judgment on caching, queues, ordering, and trade-offs, not just service names.

Interviewer may ask next
What if each conversation must keep strict message order, even under heavy load?

I would keep the same basic design, but I would put more focus on sequence IDs inside the Message Service. The main change is that each conversation needs its own order number, so the server can place new messages in a clear order before fan-out starts. MySQL still stores the final record, and the queue still carries the background work. If two messages arrive close together, the service must assign and save the order before pushing the event onward. That keeps the chat view stable on every device. Redis can still help with hot reads, but it should not decide the order. The downside is that strict ordering can slow the write path a little and may reduce how much we can parallelize.

What if users send photos or files and we must scan them first?

I would keep the same architecture, but I would make the Attachment Service do more work before the file is shared. The file still goes to object storage, but the service should scan it, save metadata, and only then let the message point to it. That fits the diagram because attachments already have their own service and S3-compatible storage. The message itself can be saved first, and the attachment can be attached after the scan succeeds, or it can stay marked as pending until the file is safe. That keeps the chat flow correct and protects users from bad files. The downside is that attachments may appear a little later, and the upload path becomes more expensive.

6. Design a top-K leaderboard.System DesignHardMeta

Question Details

Design a scalable top-K leaderboard that accepts score updates and returns globally or segment-specific ranked results. Cover ranking storage, update and query paths, tie handling, time windows, sharding, caching, durability, and the use and limitations of sorted sets.

Short Interview Answer (30-60 seconds)

At a high level, I would treat this as a fast ranking system with safe writes. The main challenge is that score updates must be saved correctly, while top-K reads must stay very quick for both global and segment-specific boards. I would break the design into the update path, the read path, and the background work that keeps Redis, the queue, and the durable store aligned. The main trade-off is speed versus extra background work and memory use.

Detailed Explanation

The goal is to keep a leaderboard that shows the top players fast. The hard part is that score updates must be saved safely, but top-K reads must stay very quick for both global and segment-specific boards. The diagram solves this by separating the update path, the read path, and the background work that keeps Redis, the queue, and the durable store in step.

Useful Questions to Ask the Interviewer
  1. Do we need all-time ranking only, or also daily, weekly, monthly, and sliding windows?
  2. Is K fixed, or can the caller ask for any top-K size?
  3. Can scores only go up, or can they also go down?
  4. Do we need global boards only, or also segment-specific boards?
Design a top-K leaderboard. diagram
How to Explain It in an Interview
1. Explain the goal and the main idea

At a high level, this is a fast ranking system with safe writes. The main thing is to keep the current leaders easy to read. The diagram does that by putting a top-K cache in front, keeping the main ranking in a Redis Sorted Set, and using background workers for durable storage and cleanup. The PHP application layer handles the logic, while PHP-FPM serves the HTTP requests.

2. Explain the update path

For the write path, the request first goes through Edge / CDN, then API Gateway (Nginx), and then the PHP-FPM Pool in PHP 8.4 / 8.5. AuthN / AuthZ / Security checks OAuth2 / JWT, API keys, RBAC / ABAC, input validation, and rate limiting. After that, the PHP service normalizes the score, builds the scope and window key, and enqueues a score.update event. The same event may arrive again, so the worker uses idempotent logic, which means the same event does not change the result twice.

3. Explain the read path

For reads, the PHP query service gets the top-K request, checks K, segment, and time window, and then tries the Redis Cluster cache layer first. On a cache hit, it returns the cached top-K right away. On a miss, it reads from the Redis Sorted Set, which is the primary ranking store. The sorted set uses score as the number to sort by and member as userId. It can answer top-K with ZREVRANGE and user rank with ZREVRANK.

4. Explain background work

The write event goes to Message Queue, which is Redis Streams or Kafka. PHP CLI Workers consume it in the background. They update the Redis Sorted Set, refresh the optional user score cache, and write durable records into the Persistent Store in MySQL or PostgreSQL. That store keeps users, profiles, score_events, leaderboard_metadata, and time_windows. This background path also supports bulk upsert and write events, so the system can rebuild data later without blocking reads. Observability comes from Metrics, Logs, Tracing, and Alerts.

5. Explain scale, ties, windows, and trade-offs

The diagram scales by hashing leaderboard_id across Redis Cluster nodes, or by partitioning on scope. Scope can be global or a segment_id. Tie handling is deterministic. The same score keeps a stable order using userId, so the result does not change randomly. Time windows use separate keys, such as all time, daily, weekly, monthly, or a sliding 24-hour window. Old entries can be removed with ZREMRANGEBYSCORE. The main trade-off is speed versus memory and freshness. Redis makes reads fast, but very large boards use more memory, and background work can make a read slightly behind a fresh write for a short time.

Engineering Considerations / Design Trade-offs

The benefit is fast reads. Redis Sorted Sets can answer top-K very quickly, and the cache can answer hot queries even faster. The benefit is also safer writes, because the worker path can save events and rebuild data later. The downside is more moving parts. We need a queue, background workers, cache keys, and durable storage. The downside is also memory cost, because very large boards can get heavy in Redis. Another downside is that some reads may briefly show slightly old data after a fresh score update.

Why Interviewers Ask This

Interviewers want to see if you can split one hard problem into simple flows. They want to know if you can choose the fast store, keep the safe store separate, and use cache the right way. They also want to see if you can think about ties, time windows, sharding, and cleanup without making the design too complex.

Interviewer may ask next
What if the same score update request is sent twice?

I would keep the same basic design, but I would make the worker path protect against duplicate events. The change affects the Message Queue, the PHP CLI Workers, and the Persistent Store. The worker should use the event id and its idempotent logic so the same update does not apply twice. That keeps the ranking correct even if Redis Streams or Kafka delivers the event again. The Redis Sorted Set still stays the main ranking store, so the read path does not change. The downside is a little more logic in the worker, so the update path becomes slightly more complex.

What if one leaderboard becomes very hot and gets most of the traffic?

I would keep the same design, but I would lean harder on sharding and the top-K cache. The change affects Redis Cluster, the cache layer, and the way we partition by leaderboard_id or scope. Consistent hashing spreads boards across nodes, so one hot board does not overload the whole system. The cache helps because many users may ask for the same top-K result. The main ranking data still lives in the Redis Sorted Set, so correctness stays the same. The downside is that one very hot board can still create uneven load, so we may need more careful capacity planning.

7. Design a typeahead search box.System DesignHardMeta

Question Details

Design a low-latency typeahead search service. Cover prefix retrieval, ranking, freshness, personalization, typo handling, multilingual input, indexing, caching, sharding, high query volume, abuse controls, and consistency tradeoffs.

Short Interview Answer (30-60 seconds)

At a high level, this is a very read-heavy system. The main goal is to show useful suggestions as soon as the user types, while also handling typos, language changes, and personal ranking. I would explain it in three parts: how the request is cleaned and protected, how the app checks cache and the search index, and how background indexing keeps the data fresh. The trade-off is that reads stay fast, but new data may appear with a small delay.

Detailed Explanation

The goal is to help a user see useful suggestions while they type. The system must answer very fast because every key press can create a request. The hard part is that it also has to handle typos, many languages, personal results, and fresh data at the same time. The diagram solves this by separating request cleaning, fast lookup, ranking, and background index updates.

Useful Questions to Ask the Interviewer
  1. How fresh do the suggestions need to be?
  2. How much should personal history affect ranking?
  3. Which languages and typo cases matter most?
Design a typeahead search box. diagram
How to Explain It in an Interview
1. Explain the goal and the main idea

At a high level, I would treat this as a low-latency search system. The user types a few letters, and we must return good suggestions very quickly. The request path is optimized for speed, while the update path runs in the background. That split is the key idea in the diagram.

2. Clean and protect the request first

The request first goes through the client, then edge security. The diagram shows WAF and DDoS protection, rate limiting per IP and user, optional auth, and input validation and normalization. That means we reject bad traffic early. We also normalize the query, so the same word is handled in a consistent way. This keeps the rest of the system simpler and safer.

3. Find candidates fast in the PHP app

The main service is a stateless PHP 8.4/8.5 app running on PHP-FPM. Nginx or OpenResty forwards the request to PHP-FPM over FastCGI, and OPcache keeps PHP bytecode ready. Inside the app, the request router, query normalizer, language detector, transliterator, typo and spell handling, and prefix expander prepare the query. The prefix router then chooses the right shard. After that, the app checks cache first. APCu is the worker-local cache, and Redis is the shared hot cache. If the cache misses, the app asks the search index cluster for prefix-optimized candidates.

4. Rank, merge, and return JSON

The app does not just return raw matches. It fetches top candidates, then the ranker orders them with relevance, popularity, freshness, and personalization. The diagram also shows external help for reranking, translation, and GeoIP or location when needed. The merger and formatter then return a small JSON response with suggestions. That small response is important because this path runs for every keystroke.

5. Keep the index fresh in the background

New content comes in through the async pipeline. The ingestion API or admin tool sends events to the message queue, then PHP CLI indexer workers build or update the search index, counters, synonyms, and cache data. A cache warmer precomputes hot prefixes. This background work does not block the search response. Observability also runs alongside it, with metrics, logs, traces, alerts, and dashboards to watch latency and errors.

6. Scale, guardrails, and trade-offs

The system scales by keeping the PHP layer stateless, using containers or VMs with autoscaling, and routing to the right shard. The main trade-off is freshness versus speed. Cache and index reads are very fast, but new data may appear a little later. Another trade-off is ranking depth versus latency. Better ranking gives better suggestions, but it can add work. The diagram accepts that balance so the box stays fast and safe.

Engineering Considerations / Design Trade-offs

The benefit is speed. Cache makes common queries very fast, and sharding spreads load across many index shards. Stateless PHP-FPM also makes horizontal scale easier. The downside is more moving parts. APCu only helps one worker, so Redis is still needed. Another downside is freshness. The index is updated in the background, so new data may take a short time to appear. Ranking also costs extra work. Better ranking can improve suggestions, but it can add latency. The system accepts that trade-off to keep the typeahead box fast.

Why Interviewers Ask This

Interviewers want to see if you can design for speed first, because typeahead is very latency sensitive. They also want to see if you can separate the fast request path from background work, use cache the right way, and keep the search index fresh without slowing users down. Good answers also show judgment about ranking, scaling, abuse control, and trade-offs.

Interviewer may ask next
What if the suggestions must reflect new data almost immediately?

I would keep the same design, but I would tighten the update path. The main change is in the async pipeline and the cache TTLs. Right now, the index builder publishes new index data in the background, and the read path can serve slightly old data for a short time. If freshness becomes more important, I would push smaller incremental updates more often and lower the cache lifetime for hot prefixes. I would still use atomic index publish, because that keeps the search index consistent during swaps. The main downside is higher write load and more cache churn. That can raise cost and add more pressure to the index cluster, so the system may lose some read speed. That is usually the right way to keep the fast path stable.

What if personalization must use the user’s recent clicks much more strongly?

I would keep the same request flow, but I would give the ranker more user context. The part that changes is the personalization store and the ranking step inside the PHP app. Today, the app can read user interests and click or select history from the relational database or a fast store, then combine that with prefix matches and freshness. If personalization matters more, I would fetch a small set of user features early in the request and pass them into the ranker. That keeps the main path simple and avoids loading too much user data. The downside is extra read work and more privacy care. It can also make ranking slower if the user profile lookup is not kept small.

Disclaimer: This interview guide is for educational and informational purposes only. It is designed to help readers prepare, but it does not guarantee any interview result, hiring decision, offer, or outcome. Interview questions, hiring criteria, and preferred answers can vary by employer, interviewer, industry, location, and time. The examples and explanations reflect the authors' research and judgment, are provided without warranties of any kind, and should not be treated as the only correct approach. Diagrams are simplified illustrations intended to highlight the main components and their interactions; actual systems and implementations may be more complex. Alternative approaches may be equally valid or better suited to a particular question, context, or interviewer. To the fullest extent permitted by applicable law, the author, contributors, and publisher are not liable for decisions made, actions taken, or losses incurred based on this guide.

Company Notice: This guide is an independent educational resource and is not affiliated with, endorsed by, sponsored by, or approved by the company named in this guide. Company names are used only to identify interview experiences commonly reported by candidates. Interview practices can change without notice, and inclusion of company-specific content does not mean these questions are official, complete, or guaranteed to be asked. To the fullest extent permitted by law, the author, contributors, and publisher are not responsible for outcomes related to use of this material.