Real Interview Questions for the Software Engineer at Mercado Libre
NewInterview Q&A
Q&A-1Explain how you would design a system to handle high traffic for a product listing page.
Reported in Software Engineer interview at MercadoLibre
The 90-second answer
A listing page is a read-heavy, mostly shared response. Most of the traffic asks for the same category or search page, so I would serve most of it from cache and keep the origin for misses and freshness-sensitive data. I would first confirm the peak shape with the interviewer: requests per second at peak, the ratio of anonymous to personalised views, and how stale a price or stock figure may be before it is wrong.
Assume, for illustration only, 3,000 page views per second normally and a 15x spike during a promotion event, so 45,000 RPS at peak. If the edge cache hits 95% of requests, the origin sees 2,250 RPS. If it hits 80%, the origin sees 9,000 RPS, which is the difference between a comfortable fleet and an outage. The hit ratio is the number to design for.
Split the page into layers with different lifetimes
| Layer | Examples | Lifetime | Where it lives |
|---|---|---|---|
| Shared listing skeleton | ids, titles, thumbnails, base ranking | 30 to 60 s | CDN edge, keyed by category, filters, page cursor |
| Price and stock | price, available units | 5 to 10 s, or event-driven purge | short-TTL cache or client overlay |
| Personalised overlay | wishlist flags, shipping offers for the user's address | per request | fetched client-side or by a small personalisation service |
Keeping personalisation out of the shared response is what lets the edge cache at all. A single Vary: Cookie would make the cache useless for anonymous traffic.
Pagination and keys
Use keyset cursors, not OFFSET. OFFSET 40000 forces the database to scan and discard 40,000 rows on every page request. Cache keys should be normalised: sort query parameters, drop tracking parameters, and cap the allowed filter combinations. Without that, filter combinations explode the key space and the hit ratio falls.
Protecting the origin
- Request coalescing: when a hot key expires, one request refreshes it and the rest wait for that result or receive the stale copy (
stale-while-revalidate). Without this, a flash sale start sends thousands of identical misses to the database together. - Event-driven invalidation for price and stock changes, with the TTL as the backstop, not the primary mechanism.
- Load shedding by tier: under pressure, serve stale skeletons and drop personalisation before failing any request.
- Read replicas or a search index for listing queries, so the primary database never serves browse traffic.
Failure modes and detection
- Stampede on promotion start: origin RPS jumps while the hit ratio falls. Detect with hit ratio per category and origin RPS per key.
- Hot category: one category holds most traffic and one shard or cache node saturates. Detect with per-node p99 and request share. Mitigate with replicated hot keys.
- Stale prices shown at checkout: a listing price differs from the checkout price. Detect by comparing listing and checkout prices in a sampled job. The fix is to revalidate price at checkout, not to shorten the listing TTL to zero.
- Cache poisoning through unnormalised query strings: unexpected key cardinality growth. Detect with cache key count per hour.
Trade-off to state out loud
Longer TTLs cut origin load and increase staleness. Shorter TTLs do the reverse. I would accept a 30-second-stale skeleton and never accept a stale price at checkout. That split is the decision the interviewer usually wants to hear.
Measure
Edge hit ratio, origin RPS, p99 of the listing service, cache node CPU and key count, and the share of requests served stale. A load test at 3x expected peak with a simulated promotion start tells you whether the coalescing actually works.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2Tell me about a time you had a conflict with a teammate and how you resolved it.
Reported in Software Engineer interview at MercadoLibre
The 90-second answer
I'll use a retry-policy disagreement from a three-person team that owned the order-status poller at Mercado Libre. A teammate wanted the poller to retry with exponential backoff and full jitter. I wanted fixed 2 s retries and moved the smarter handling into the queue consumer, because I thought the poller should stay dumb. We went back and forth in PR comments for three days and both got sharper and more annoyed.
What I changed was the question I was arguing. I stopped defending a design and listed the things we could measure: request volume to the status endpoint at peak, how many duplicate status events the consumer could absorb, and what a retry storm would do to the upstream dependency. Then I asked for 30 minutes and proposed a test instead of a verdict: replay a week of logs through both policies in staging.
| Step | Fixed 2 s (my option) | Backoff + full jitter, cap 30 s (teammate's option) |
|---|---|---|
| Peak calls/min, replay of a hypothetical 1,800 req/min burst | 1,800 | about 700 |
| Duplicate status events reaching consumer | up to 3 per order | up to 1 per order |
| Worst-case delay to final status | 6 s | 30 s |
The replay showed the teammate was right on load, and I was right that duplicates had to be handled. The consumer already keyed on (order_id, status_version), so duplicates were harmless and the consumer change I had proposed was unnecessary. We shipped backoff with full jitter and a 30 s cap. I wrote the decision into the service's design doc with the replay numbers, so the next person would not reopen it from memory.
What I'd say if probed
The conflict cost us three days, and the honest lesson is that I was defending a position for longer than I was testing it. Now I ask early what would change my mind. If a disagreement is about a fact, I try to find the cheapest way to check the fact. If it is about taste, I say so and let the owner decide.
I also did not fully resolve the relationship in one meeting. The teammate and I agreed on the decision but still disagreed on how it had been reached, so I asked for feedback on my part in it. That conversation was less comfortable than the replay, and it was the one that changed how I review their code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3How do you ensure code quality in your projects?
Reported in Software Engineer interview at MercadoLibre
The 90-second answer
I treat quality as a set of checks aimed at the failures that hurt a marketplace most: a duplicated order, a refund issued twice, a checkout that silently returns the wrong price. Generic style rules come last. I assume a service owned by a team of five to eight engineers, deploying several times a day, with consumers I don't fully control. Each check I add has to catch one of those failures, or I drop it.
The layers, in the order a change meets them:
| Layer | What it catches | Cost I accept |
|---|---|---|
| Small PRs, under about 400 changed lines | Review that actually reads the diff | Some features need stacked PRs |
Lint, type checks (mypy strict or javac -Xlint:all -Werror) | Interface drift, nullability bugs | Minutes of CI on every push |
| Unit and property tests on money and state code | Rounding, state transition errors | Test-writing time on the hot paths |
| Consumer contract tests for the order API | Breaking a client we never talk to | A shared contract repo to maintain |
| Canary at 1% of traffic for 15 minutes, with auto-rollback | Failures that only show under real load | Slower rollout for urgent fixes |
I don't trust a global coverage percentage. I require coverage on changed lines and on the idempotency and money paths, because a 90% repo number can hide an untested refund handler.
A concrete check
For any endpoint that moves money, I write the retry test first. Hypothetical example: a refund handler where a client retries after a timeout.
def test_retried_refund_is_not_applied_twice(client, refunds_for):
headers = {"Idempotency-Key": "k-123"}
body = {"amount_cents": 1500}
r1 = client.post("/orders/42/refunds", headers=headers, json=body)
r2 = client.post("/orders/42/refunds", headers=headers, json=body)
assert r1.status_code == 201
assert r2.json()["id"] == r1.json()["id"]
assert len(refunds_for(42)) == 1The test fails loudly if someone removes the key lookup in a refactor, which a reviewer skimming the diff would miss.
Where it breaks down
The main failure mode is a test suite that passes while production drifts: mocks that no longer match the real dependency, or a contract test that only runs in one consumer's pipeline. I detect this with the canary metrics: error rate by status code and by consumer, compared to the baseline for the last 24 hours. If a new error code appears that no test exercised, that is the signal to add a test before the next deploy, not to lower the bar.
I also push back on quality work that nobody owns. Each gate has a named owner, and a flaky test gets fixed or quarantined within a day. A check that people learn to ignore is worse than no check, because it teaches the team that green means nothing.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4Tell me about a project that slipped. What did you do?
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 90-second answer
The project was moving our shipping-label service off a synchronous call into the logistics monolith and onto its own event-driven service. We committed to six weeks and finished in eleven. It slipped because we estimated from the happy path and never wrote a contract test for the legacy service's retry behaviour, which was undocumented and turned out to matter.
When it was clear we were late, I stopped reporting percent complete and rebuilt the remaining work as a list of unknowns. Figures below are hypothetical, for illustration. We had 14 endpoints left, and 3 of them had retry semantics that only existed in the legacy code. I took that list to the PM and tech lead with two options: cut to the 9 endpoints that serve about 95% of label requests and ship in week seven, or keep the full scope and move to week eleven. We cut scope. The other 5 went into a follow-up with a named owner and a date, so the slip was visible rather than absorbed.
Working the cut scope
I ran the new service in shadow mode, mirroring live traffic and diffing responses against the monolith. Peak was about 1,200 label requests per second. A 0.1% diff rate at that load is 1.2 mismatches per second, roughly 72 per minute or 4,300 per hour. Nobody can review that by hand, so I added a per-endpoint diff counter with an alert on the rate, and sampled the mismatches that did get through.
The rollout exposed what the estimate missed. At 1% traffic, p99 went from 40 ms to 180 ms once the HTTP client pool saturated at 20 connections under bursts from one large seller. The fix was per-tenant connection limits and a bulkhead, not a bigger pool. I would not have found this without the rollout staged by tenant size.
| Option | Ship date | Risk accepted |
|---|---|---|
| Full scope | week 11 | none beyond the estimate |
| Cut to 9 endpoints | week 7 | 5 endpoints on the monolith, dual-run for another quarter |
| Cut and freeze | week 7 | legacy retry semantics kept as a documented contract |
Failure modes I watched for
Shadow mode can hide a divergence that is consistent but wrong on both sides. Because the diff only catches disagreement, a retry that both systems handle badly looks like a pass. I checked a sample of matched responses against the spec, not only the diffs.
Cutting scope also moves the cost. The five deferred endpoints kept the monolith alive for another quarter, so I tracked their owner and the dual-run cost in the same review as the launch.
What I changed afterwards
I now put every undocumented behaviour on the estimate as a line item with an owner before the number is committed. Unknowns get their own time box, and a slip gets reported as a changed set of options with a recommendation, not a new date alone.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Design an LRU cache with O(1) get and put.
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 90-second answer
I'd pair a hash map with a doubly linked list. The map gives O(1) lookup from key to node. The list keeps nodes in recency order, with the most recent at the head and the eviction candidate at the tail. Both get and put only relink a constant number of pointers, so each is O(1). Before writing code I'd confirm three things: whether keys and values are bounded in size, whether the cache is shared across threads, and whether entries need a TTL. The first two change the design. The third changes the question.
Implementation (Python 3.12)
class Node:
__slots__ = ("key", "val", "prev", "next")
def __init__(self, key=None, val=None):
self.key, self.val = key, val
self.prev = self.next = None
class LRUCache:
def __init__(self, capacity: int):
if capacity <= 0:
raise ValueError("capacity must be positive")
self.cap = capacity
self.map: dict[int, Node] = {}
self.head, self.tail = Node(), Node() # sentinels, no edge cases
self.head.next, self.tail.prev = self.tail, self.head
def _unlink(self, n: Node) -> None:
n.prev.next, n.next.prev = n.next, n.prev
def _push_front(self, n: Node) -> None:
n.prev, n.next = self.head, self.head.next
self.head.next.prev = n
self.head.next = n
def get(self, key: int) -> int:
n = self.map.get(key)
if n is None:
return -1
self._unlink(n)
self._push_front(n)
return n.val
def put(self, key: int, value: int) -> None:
n = self.map.get(key)
if n is not None:
n.val = value
self._unlink(n)
self._push_front(n)
return
if len(self.map) == self.cap:
victim = self.tail.prev
self._unlink(victim)
del self.map[victim.key]
n = Node(key, value)
self.map[key] = n
self._push_front(n)The sentinels remove every empty-list and single-node branch. Without them, the unlink and push code needs guards for head and tail, and that is where interview implementations usually break.
Trace (capacity 2, hypothetical sequence)
| Step | Operation | Result | List, most recent first |
|---|---|---|---|
| 1 | put(1, a) | none | 1 |
| 2 | put(2, b) | none | 2, 1 |
| 3 | get(1) | a | 1, 2 |
| 4 | put(3, c) | evicts 2 | 3, 1 |
| 5 | get(2) | -1 | 3, 1 |
Step 3 is the one candidates miss. A read counts as a use, so it moves the entry to the front. Otherwise step 4 would evict 1 instead of 2.
Alternatives
collections.OrderedDict with move_to_end and popitem(last=False) gives the same complexity in about ten lines. In an interview, name it, then write the explicit version so the pointer work is visible. In Java, LinkedHashMap with accessOrder=true and an overridden removeEldestEntry does the job, but it is not thread-safe.
Concurrency
get mutates the list, so it is a write. A plain RLock around both methods is correct and simple. A ReadWriteLock does not help here, because reads still reorder. Under contention, sharding by key hash into N independent caches trades exact global LRU order for throughput. Each shard holds capacity / N entries, so a hot key can evict cold keys that a global cache would keep. Measure hit rate before and after sharding.
Failure modes to name
- Memory is bounded by entry count, not bytes. A few large values can exceed the budget. Track total bytes and evict until under the limit.
- Stale data. An LRU with no TTL serves old values indefinitely if they stay hot. Add expiry and check it on
get. - Eviction storms. A scan larger than capacity flushes the working set. Detect it with a falling hit rate, and consider an admission filter or a segmented LRU.
- Lock hold time. Keep the critical section to pointer work. Never call a loader or perform I/O while holding the lock.
When not to build this
If the working set fits in memory and the process is a single thread, functools.lru_cache is enough. If the cache must survive restarts or span hosts, use Redis or Memcached and accept the network round trip, which is typically around 0.2 to 1 ms in-datacenter compared with tens of nanoseconds for an in-process lookup.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Explain connection pooling and why it matters.
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 60-second answer
A connection pool keeps a bounded set of open database connections and lends them to requests. A request takes a connection, runs its queries, and returns it. Opening a connection is expensive: a TCP handshake, TLS, authentication, and on PostgreSQL a new backend process per connection. The pool pays that cost once and reuses the connection. It also caps how many connections reach the database, and that limit usually matters more than the latency saving.
Before I design anything I'd ask two things: which database and driver, and how many service instances run. The pool is per process. Forty pods with a pool of 20 means up to 800 connections aimed at one database, which can exceed what the server allows before any single pod looks unhealthy.
Sizing with Little's law
Concurrent connections needed = arrival rate × time each request holds a connection. Hypothetical figures, to show the arithmetic:
| Input | Value |
|---|---|
| Requests/s | 1,200 |
| Connection hold time per request | 8 ms |
| Average busy connections | 1,200 × 0.008 = 9.6 |
A pool of 10 leaves almost no headroom. If p99 hold time doubles under load, the busy count doubles, requests queue for a connection, and latency climbs while database CPU stays low. That symptom is easy to misread as a slow query. Past the database's real concurrency, a bigger pool just moves the queue inside the database.
Failure modes and detection
| Symptom | Likely cause | How to detect |
|---|---|---|
| p99 rises, DB CPU low | Pool exhausted, callers waiting for a connection | Pool wait-time metric, active vs max |
too many connections from the server | Pods × pool size exceeds server limit | Server-side connection count grouped by client |
| Errors after a failover or LB reset | Idle connections killed by a network device | Set max lifetime below that timeout, validate on borrow |
| Steady climb in active connections | Code path that never returns the connection | Active count rising monotonically under constant load |
The most common self-inflicted cause is a transaction held open across a remote HTTP call. The connection sits idle inside the transaction, so hold time includes network latency to another service. Keep transactions short and do external calls before BEGIN or after COMMIT.
Trade-offs and when not to pool
For many short-lived clients, such as serverless functions or hundreds of small workers, an external pooler like PgBouncer in transaction mode multiplexes them onto a few server connections. Transaction mode breaks session state: session-level prepared statements, SET values and advisory locks do not survive across transactions unless the pooler and driver are configured for it. Session mode is safer but gives much less multiplexing.
Defaults I'd check rather than trust: HikariCP 5.x uses a maximum pool size of 10, a 30 s connection timeout and a 30 min max lifetime. Those are fine starting points, but they need to be set against your server limit and the failover timeout, not left at whatever the framework generated.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7Explain JWT structure and common pitfalls.
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 90-second answer
A JWT is three base64url segments joined by dots: header.payload.signature. The header names the algorithm (alg) and usually a key id (kid). The payload holds claims. The signature covers the first two segments. The payload is signed, not encrypted, so anyone holding the token can read it. Verification is the whole job: check the signature with a key you trust, pin the algorithm, then check iss, aud, exp and nbf against your own configuration.
Most production failures come from skipping one of those steps, or from trusting the token's own header to tell you how to verify it.
Structure, concretely
eyJhbGciOiJSUzI1NiIsImtpZCI6ImsxIn0 -> {"alg":"RS256","kid":"k1"}
eyJzdWIiOiJ1XzkxMiIsImF1ZCI6ImNoZWNrb3V0IiwiZXhwIjoxNzAwMDAwMzAwfQ -> {"sub":"u_912","aud":"checkout","exp":1700000300}
<signature bytes>The payload decodes to registered claims from RFC 7519: iss, sub, aud, exp, nbf, iat, jti. Your own claims go alongside them. Clock values are NumericDate, seconds since the epoch.
Pitfalls, in the order I'd raise them
| Pitfall | What goes wrong | Check |
|---|---|---|
Trusting alg from the header | alg: none is accepted, or an RS256 public key is reused as an HMAC secret | Hard-code the allowed list per key |
Missing aud check | A token minted for service A is accepted by service B | Compare against your service id |
No exp, or a long one | A stolen token stays valid for weeks | Access tokens in minutes, not days |
| Sensitive data in the payload | Anyone with the token reads it | Keep PII and roles you would not show a browser out |
| Revocation assumed | A signed token stays valid until exp | Short lifetime plus a denylist keyed on jti |
Token in localStorage | Any XSS reads it | HttpOnly, Secure, SameSite cookie for browsers |
kid used as a file path or query | Key lookup injection | Map kid to a fixed key set from JWKS |
Verification, pinned
# PyJWT 2.x, Python 3.11
claims = jwt.decode(
token,
public_key,
algorithms=["RS256"], # pinned, never read from the header
audience="checkout",
issuer="https://auth.internal",
leeway=30, # tolerate small clock skew, state the value
)RFC 8725 (JWT Best Current Practices) is the reference for these rules. Check the library's changelog before you rely on defaults, because defaults have changed between major versions.
Mercado Libre context
Across many services and countries, validate once at the gateway, cache the JWKS document, and refresh keys on an unknown kid with a rate limit. Hypothetical figure: if each service fetches JWKS per request at 5,000 rps, that is 5,000 outbound calls a second to the auth server. Caching for 10 minutes brings that to one fetch per instance per 10 minutes. Key rotation then needs an overlap window longer than the cache TTL, or valid tokens fail for a few minutes.
Follow-ups I'd expect
Why not store state server-side? A session store gives instant revocation at the cost of a lookup on every request. Signed tokens avoid that lookup, so the revocation gap has to be accepted, or paid for with a denylist. That trade-off is the real answer to 'when would you not use JWT'.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Design a leaderboard for millions of players.
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 90-second answer
First I'd pin down what is ranked (cumulative points, best single game, or a weekly window), how often scores change, and whether a player needs their own exact rank or only the top 100. Assume 5 million active players, 20,000 score events per second at peak, and reads far outnumbering writes.
The core is one sorted set per window in Redis. ZINCRBY applies a score change, ZREVRANGE key 0 99 returns the top 100, and ZREVRANK gives one player's position. Each write is O(log N). For N = 5,000,000, log2 N is about 22, so a write costs roughly two dozen comparisons and a top-100 read is O(log N + 100). Nothing scans the board.
The event log is the source of truth. Scores come from an append-only stream of game events, and the leaderboard is a projection that can be rebuilt by replaying it. Redis persistence is not an audit trail: with asynchronous replication, a failover can lose the last writes.
Tie-breaking. Redis scores are IEEE doubles, which hold integers exactly up to 2^53. Pack points and time into one score. Points stay below 2^20 (about one million). Use seconds since an epoch as a 31-bit value, inverted so earlier wins: score = points × 2^31 + (2^31 − 1 − ts). The maximum is 2^51, safely inside 2^53. Trace: player A reaches 900 points at ts=100 and player B reaches 900 at ts=90. A's score carries the term 2^31−1−100, B's carries 2^31−1−90. B's is larger by 10, so B ranks above A, which is the intended result.
Sharding. Five million members fit in one node's memory at this scale (hypothetically about 100 bytes per member, so roughly 500 MB), but write throughput and failover risk argue for splitting by hash of player_id into 8 shards. That gives 2,500 writes per second per shard. A global top 100 asks each shard for its top 100, then merges 800 candidates in the application and keeps 100. A player's exact global rank is the sum over shards of ZCOUNT key (score +inf plus one, which is eight O(log N) calls.
Caching. The top 100 changes constantly, but polling clients at one request per second during a viral event would otherwise drive the read load. Compute the merged top 100 once per second and serve that copy to everyone.
Failure modes and detection. A failover that drops writes shows up as the projection falling behind the event log's committed offset; detect it by comparing offsets and replay from the last durable offset. Double-applied events inflate scores, so store the last applied event sequence per player and skip anything at or below it. Detect drift with a nightly check that sums each player's points in the projection against the ledger.
When not to use this. If the board is small or needs exact ranks with transactional consistency against the order database, a SQL table with an index on the score is simpler and easier to reason about. For a weekly board, use a key per week with a TTL, so old windows expire without a cleanup job.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9Explain sharding vs partitioning vs replication.
Reported in interview-rounds/content/interviews/mercado-libre-5.md at main · sumitsingh4411/interview-rounds
The 90-second answer
These solve three different problems, and they stack. Replication keeps copies of the same data on several nodes, for read capacity and failover. Partitioning splits one logical table into disjoint pieces, usually inside one database server, to bound index size and make maintenance cheap. Sharding is partitioning where each piece lives on a different node with its own storage, so it adds write capacity but makes every cross-piece query and transaction expensive. In a marketplace I would shard orders by buyer, replicate the listing catalog for reads, and partition order history by month for retention.
I'd first confirm the bottleneck. If the primary is CPU-bound on reads, replicas help. If the table is too big to index or vacuum in time, partitioning helps. Only if a single primary cannot absorb the write rate do I shard.
| Technique | Copies of a row | Where pieces live | Solves | Costs |
|---|---|---|---|---|
| Replication | N identical copies | N nodes | read throughput, failover | replica lag, stale reads |
| Partitioning | 1 | one server | index size, pruning, retention drops | planner overhead, no cross-node gain |
| Sharding | 1 (per shard, optionally replicated) | many nodes | write throughput, storage | cross-shard joins, rebalancing, no global unique constraints |
Replication lag breaks read-your-writes. A buyer places an order on the primary, then loads /orders from a replica 300 ms behind and sees nothing. Route a session's reads to the primary for a short window after a write, or pass the commit LSN and wait for the replica to reach it. Detect this with a metric on replica lag per replica and a canary that writes then reads.
Hash sharding and resharding. Hash buyer_id modulo 3 across three shards. Going to four shards with the same modulo moves 75% of keys, because a key stays only when its hash has the same residue mod 3 and mod 4, which is 3 of 12 residues. Consistent hashing or a fixed logical shard count (say 1024 virtual shards mapped to nodes) moves roughly 1/4 of data instead, and only the mapping changes when you add nodes.
The query that hurts. The seller dashboard needs orders for a seller, but orders are spread by buyer. Options: fan out to every shard (cost grows with shard count, tail latency is the slowest shard), or maintain a second projection keyed by seller, updated asynchronously. I would take the projection and accept that the seller view is seconds behind, stating that in the contract.
Failure modes I'd name. A hot shard from one large seller or a skewed key, detected by per-shard QPS and p99 divergence. A partition key that cannot be changed later, so pick it for access patterns, not for uniform distribution alone. Uniqueness across shards, which needs a central allocator or ids that embed the shard, such as a Snowflake-style id with the shard bits in it.
So: replicate for reads, partition for size and retention, shard only when the write path forces it, and choose the shard key from the query you most need to keep local.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Design a ride-sharing service like Uber.
Reported in interview-rounds/content/interviews/mercado-libre-3.md at main · sumitsingh4411/interview-rounds
The 90-second answer
I'd start by narrowing scope: rider request, driver matching, and trip state. Pricing, payments and surge are separate services. I'd assume a Mercado Libre style deployment across a few large cities in Brazil and Mexico, with drivers on low-end Android phones and patchy 3G/4G. Hypothetical sizing for the design: 1M active drivers each sending location every 4 s is 250k location writes/s, and 100k ride requests at peak is about 1,700 requests/s.
The design has three separate paths with different consistency needs. Location ingest is high volume and tolerates loss, so it stays in memory. Matching is latency-sensitive and must not double-assign a driver. Trip state is low volume and must be correct.
Location ingest. Drivers post pings to a stateless gateway, which writes to an in-memory geospatial index partitioned by H3 cell at resolution 8 (average edge about 0.46 km). Writes never touch the trip database. A ping older than 15 s is treated as stale and the driver drops out of candidate sets. Mobile clients buffer pings offline and send only the latest one on reconnect, so a backlog never floods the index.
Matching. A ride request reads the rider's cell plus its k=1 ring of neighbours, takes the candidates that are online and idle, and ranks them by ETA from the routing service, not straight-line distance. Offers go out one at a time with a 10 s timeout, so one driver never holds two offers.
Assignment is a conditional write. Trip state lives in a relational store with a version column:
UPDATE trips SET driver_id = :d, state = 'assigned', version = version + 1
WHERE id = :t AND state = 'requested' AND version = :v;If zero rows change, another path already won, and the matcher moves to the next candidate. The rider's create request carries an Idempotency-Key, so a mobile retry after a dropped connection returns the same trip rather than a second one.
| Step | Time | Result |
|---|---|---|
| rider posts request | t=0 ms | trip created, state requested |
| candidate query over 7 cells | t=12 ms | 9 drivers |
| ETA ranking | t=40 ms | driver D1 first |
| offer to D1 | t=41 ms | D1 declines at t=3.1 s |
| offer to D2 | t=3.2 s | D2 accepts at t=4.0 s |
| conditional update | t=4.0 s | 1 row, state assigned |
Trade-offs. Partitioning by city keeps each shard small and lets a bad region fail alone, but a ride near a border needs cross-shard lookup, so I'd query neighbouring shards only when the ring crosses a boundary. A single global matcher is simpler but becomes the bottleneck. Storing locations in a database instead of memory costs throughput I don't need.
Failure modes and detection.
- Double assignment: detected by a rejected conditional write count; alert if any driver appears in two
assignedtrips. - Stale locations: watch the ingest lag histogram; if p99 lag passes 15 s the index is serving ghosts.
- Matching slowdown: p99 match latency rising past 2 s usually means the routing service is saturated, so fall back to haversine ranking and mark the result as degraded.
- Offer fatigue: falling acceptance rate with stable supply points to bad ETAs, not too few drivers.
I'd finish by naming what I'd build first: the location index and the conditional assignment, since everything else depends on them being correct under load.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11How do you run an incident and the postmortem after?
Reported in interview-rounds/content/interviews/mercado-libre-3.md at main · sumitsingh4411/interview-rounds
The 90-second answer
First I make sure the incident has an owner. One person is incident commander and coordinates; they do not debug. I name a comms lead who posts status updates on a fixed cadence (every 15 minutes at severity 1) and a scribe who keeps a timeline in the incident channel with timestamps. I state the impact in one sentence: which flows are broken, which regions, roughly what fraction of checkouts or payment attempts are failing. Then I stabilise before I diagnose. If a deploy landed in the last hour, I roll it back or flip the feature flag off first and investigate afterwards. Restoring service is the goal during the incident; root cause can wait until it is safe to look.
Mechanism during the incident
The commander keeps a short list of hypotheses and what evidence would confirm or rule out each one, so the team does not chase whichever graph moved last. Typical checks on a marketplace service are error rate by endpoint, p99 latency against the baseline, saturation of the connection pool and downstream timeouts, and the diff of what changed in the last hour. A concrete trace might read: 14:02 checkout p99 at 180 ms against a 60 ms baseline (hypothetical figures); 14:06 pool at 20/20 connections with waiters queuing; 14:09 flag off for the new recommendation call; 14:11 p99 back to 65 ms. That timeline is what the postmortem is built from, so the scribe's notes matter more than anyone's memory.
The postmortem
I write it within a few business days while the timeline is fresh. It is blameless in practice, not just in wording: it asks why the system allowed the failure, not who typed the command. It has four parts: impact (duration, users and revenue affected, measured numbers), timeline, the contributing causes (usually more than one, for example a missing timeout plus a retry storm), and what detected it and how long detection took. Each action item has one owner, a due date and a ticket, and I put the items in a review meeting with someone outside the team who can push back on them.
Failure modes I watch for
A restart that clears the symptom gets recorded as the cause, so the bug returns in the next peak. Action items with no owner stay open for a year. Postmortems that name individuals teach people to hide the next incident. I track action-item closure as a metric and bring overdue items to the engineering review. If the same failure class appears twice, the second postmortem should be about why the first one's fix did not hold.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Walk me through how you would construct a binary tree from its preorder and inorder traversals.
Reported in interview-rounds/content/interviews/mercado-libre-3.md at main · sumitsingh4411/interview-rounds
The 90-second answer
Assume the values are distinct. Without that, the inorder position of a value is ambiguous and the tree is not unique, so I'd ask first. The preorder list gives the root as its first element. Find that root in the inorder list: everything left of it is the left subtree, everything right of it is the right subtree. Recurse on each side with the matching slice of preorder. A hash map from value to inorder index makes each root lookup O(1), so the whole build is O(n) time and O(n) space.
The one detail that breaks most first attempts: the preorder cursor advances once per node, in preorder order, so the left recursion must consume its nodes before the right recursion starts. Advance the cursor when you create the node, not when you look up the index.
# Python 3.11
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def build_tree(preorder, inorder):
pos = {v: i for i, v in enumerate(inorder)}
idx = 0
def helper(lo, hi):
nonlocal idx
if lo > hi:
return None
root_val = preorder[idx]
idx += 1
mid = pos[root_val]
node = TreeNode(root_val)
node.left = helper(lo, mid - 1)
node.right = helper(mid + 1, hi)
return node
return helper(0, len(inorder) - 1)Trace. preorder [3, 9, 20, 15, 7], inorder [9, 3, 15, 20, 7], so pos = {9:0, 3:1, 15:2, 20:3, 7:4}.
| call | range [lo, hi] | preorder[idx] | root | mid | left size |
|---|---|---|---|---|---|
| helper(0, 4) | whole | 3 | 3 | 1 | 1 |
| helper(0, 0) | [9] | 9 | 9 | 0 | 0 |
| helper(2, 4) | [15,20,7] | 20 | 20 | 3 | 1 |
| helper(2, 2) | [15] | 15 | 15 | 2 | 0 |
| helper(4, 4) | [7] | 7 | 7 | 4 | 0 |
The resulting tree is 3 with left child 9 and right child 20, and 20 has children 15 and 7. Checking it: its inorder walk gives 9 3 15 20 7 and its preorder walk gives 3 9 20 15 7, matching the inputs.
Alternatives. An iterative version uses an explicit stack and a pointer into inorder: push each preorder value, and whenever the stack top equals inorder[ptr], pop it and advance ptr, attaching the new node as the right child of the last popped node. It is also O(n) and avoids recursion. I would write the iterative form if the input could be deep, and say so.
Rebuilding from inorder plus postorder works the same way with the last postorder element as root and the recursion done right subtree first. Building from preorder alone cannot recover the shape, because a single chain of left and right children gives the same preorder sequence. The inorder list is what carries the split information.
Failure modes to name.
- Duplicate values: the map keeps only the last index, so the tree comes out silently wrong. Fix it with a contract that values are unique, or by carrying indices in the input instead of values.
- Inputs that are not permutations of each other, or differ in length:
pos[root_val]raisesKeyErroror the cursor runs past the list. Validate lengths and set equality up front and return a clear error. - Stack depth: on a skewed tree of 10^5 nodes, the default CPython recursion limit of 1000 is exceeded. Use the iterative version, or raise the limit only if you own the process.
In a test, I'd cover a single node, a left-only chain, a right-only chain, a full tree, and the empty input, then property-check random trees by serializing them and rebuilding.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13Find the lowest common ancestor of a binary tree.
Reported in interview-rounds/content/interviews/mercado-libre-3.md at main · sumitsingh4411/interview-rounds
The 60-second answer
First I'd confirm three things: are both target nodes guaranteed to be in the tree, can values repeat, and do nodes have parent pointers? Assuming both targets exist, values are unique and there are no parent pointers, I'd use one post-order DFS. Each call returns the target node if it finds one in its subtree, otherwise None. If the left and right recursive calls both return non-null, the current node is the split point and is the answer. If only one side returns non-null, I pass that result up. A node that is itself a target counts as an ancestor of the other target, so p can be the answer when it sits above q.
# Python 3.12
def lca(root, p, q):
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left and right:
return root
return left or rightTrace on this tree, with lca(7, 4):
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4At node 5 the left call returns None (6 is neither target) and the right call descends into 2, where 7 and 4 return separately. Node 2 has both sides non-null, so it returns 2. Back at 3, the left side gives 2 and the right side gives None, so the result is 2. For lca(5, 1), node 5 is a target and returns immediately, node 1 is a target and returns, and 3 is the split.
Cost. Time is O(n) because each node is visited at most once. Space is O(h) for the call stack, where h is the height. On a skewed tree of 100,000 nodes, h is 100,000, and CPython's default recursion limit of 1000 raises RecursionError. I'd mention that and either rewrite with an explicit stack or accept the limit for the interview.
Failure modes.
- A target missing from the tree. The function returns the other target, or
None, with no error. Fix: count how many targets each subtree contains and only accept a split when both counts reach 2. Otherwise run a membership check first. - Aliasing with
==instead ofis. Duplicate values break the function if compared by value. Use identity, or compare on a unique key. - Deep recursion, covered above.
Variants to offer next
- With parent pointers: walk up from
pand store every ancestor in a set, then walk up fromquntil you hit a stored node. O(h) time and space, no recursion. - Many queries on a fixed tree: precompute binary lifting tables in O(n log n), then answer each query in O(log n).
- Binary search tree: use the ordering. Start at the root, go left if both values are smaller, right if both are larger, and return the current node otherwise. This runs in O(h) without visiting the whole tree.
Test with p == q, one target as the ancestor of the other, a missing target, and a skewed tree. Those four cases cover most of the bugs I'd expect to see in a live round.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14Design a Shopping Cart Checkout system.
Reported in MercadoLibre's Interview Process (2026)
The 90-second answer
I'd start by pinning scope: a cart belongs to a buyer, checkout turns the cart into an order plus a payment, and stock is reserved for a bounded window. I'd assume about 2,000 checkouts per second at peak (hypothetical), a 30-minute reservation hold, and payment methods that settle asynchronously, such as Pix and boleto, alongside cards.
The core rule: checkout is a state machine, and every side effect is tied to one transition. The cart is mutable and cheap. Checkout creates an order in PENDING_PAYMENT, reserves stock with a TTL, and calls the payment provider using a key derived from the order id. The order is confirmed on a payment event, never on the HTTP response.
Trace of one checkout with a lost response
- Client sends
POST /checkoutswithIdempotency-Key: k1andcart_version: 7. - The service checks the cart version (optimistic lock), creates order 9001 as
PENDING, and reserves stock with a conditional update:UPDATE stock SET reserved = reserved + 2 WHERE sku = ? AND available - reserved >= 2. It returns202with the order id. - The provider call uses the key
order-9001-attempt-1. It times out at 2 s and the response is lost. - The client retries with
k1at 2.5 s. The key is found and the same202is replayed. No second order exists. - The provider's
payment.approvedwebhook arrives. The order moves toPAIDand the reservation becomes a sale. A unique constraint on(provider, event_id)drops duplicate webhooks. - For a Pix payment with no webhook after 30 minutes, a sweeper releases the reservation and moves the order to
EXPIRED.
Arithmetic that shapes the design
2,000 checkouts/s over a 1,800 s hold means up to 3.6 M live reservations. A single stock row is a hotspot for a flash sale: 500 units sold in a few seconds serialises every checkout on one row. I'd shard the stock counter per SKU into buckets (for example 16 buckets of 31 units each) and reserve against a bucket chosen by hash of the order id. Reservation TTL must exceed the longest payment window of any method offered, or a boleto paid on day two lands on stock that was already released.
Trade-offs
Cart, order and stock in one transactional database is the simplest correct design, and it holds until the write path outgrows one shard. Once the payment provider is involved you need a saga with compensations: reserve, charge, confirm, and release on failure. Do not try two-phase commit with the provider, because it does not participate in your transactions.
Failure modes and how I'd detect them
- Oversell: reserved exceeds available. A reconciliation job compares the stock ledger with order lines and alerts on any nonzero drift.
- Double charge: attempt keys reused or regenerated on retry. Count provider charges per order id and alert when any count exceeds 1.
- Lost webhook: orders stuck in
PENDINGpast SLA. Alert on the age of the oldest pending order and reconcile by polling provider status. - Price drift: the catalogue price changes between cart and payment. Snapshot prices when the checkout is created and return
409if the catalogue has moved.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Implement a function that returns the largest value from a queue while maintaining a history of those values.
Reported in MercadoLibre's Interview Process (2026)
The 60-second answer
I'll assume a FIFO queue of comparable values with enqueue and dequeue, and that "history" means an append-only log of every maximum returned by the query. If you meant the maximum at every queue state, the same structure works with one line changed in enqueue. I'd also ask whether the history is bounded, because that decides the memory story.
A naive scan makes each query O(n). I keep a second deque, a monotonic decreasing deque of candidates for the maximum. The front is always the current maximum. Enqueue pops smaller values from the back, dequeue removes the front only when it is the value leaving the queue, and the query is O(1). Every value enters and leaves that deque at most once, so each operation is amortised O(1).
# Python 3.12
from collections import deque
class MaxQueue:
def __init__(self):
self._q = deque()
self._maxq = deque()
self._history = []
def enqueue(self, x):
self._q.append(x)
while self._maxq and self._maxq[-1] < x:
self._maxq.pop()
self._maxq.append(x)
def dequeue(self):
x = self._q.popleft()
if self._maxq and self._maxq[0] == x:
self._maxq.popleft()
return x
def largest(self):
if not self._maxq:
raise IndexError("empty queue")
m = self._maxq[0]
self._history.append(m)
return m
def history(self):
return list(self._history)The < comparison keeps equal values in the candidate deque. That matters for duplicates: with [5, 5] in the queue, dequeuing the first 5 must pop exactly one candidate.
Trace. Enqueue 3, 1, 4, 1, 5.
| Step | Queue | Candidate deque | Note |
|---|---|---|---|
| enqueue 3 | [3] | [3] | |
| enqueue 1 | [3, 1] | [3, 1] | 1 kept, nothing smaller behind it |
| enqueue 4 | [3, 1, 4] | [4] | pops 1, then 3 |
| enqueue 1 | [3, 1, 4, 1] | [4, 1] | |
| enqueue 5 | [3, 1, 4, 1, 5] | [5] | pops 1, then 4 |
| largest() | returns 5, history = [5] | ||
| dequeue() | [1, 4, 1, 5] | [5] | returns 3; front 5 ≠ 3, nothing removed |
| largest() | returns 5, history = [5, 5] |
Complexity. Enqueue, dequeue and largest are amortised O(1) time. Space is O(n) for the queue plus at most O(n) for candidates. History grows by one entry per query, so it is O(q) for q queries.
Failure modes I'd raise.
- History is unbounded. A long-lived service calling
largest()in a loop will leak memory. I'd cap it with a fixed-size ring buffer or emit the entries to a log. - Empty queue.
largest()must raise or return a sentinel, and the choice needs to be stated in the contract. - Concurrency. The two deques must change together. Under multiple threads I'd wrap both operations in one lock, or use a single-writer design. Without that, a dequeue can race with enqueue and leave the candidate front stale.
- Mutable values. If values can change after enqueue, the monotonic invariant breaks. I'd require immutable or copied values.
If the interviewer pushes toward a sliding window maximum, this is the same deque technique, and I'd point that out rather than build a separate structure.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16How does React reconciliation, the diffing algorithm, work?
Reported in interview-rounds/content/interviews/mercado-libre-1.md at main · sumitsingh4411/interview-rounds
The 90-second answer
Reconciliation is how React turns a new tree of elements returned from a render into the minimal set of changes to the DOM. React does not diff the real DOM. It diffs two element trees: the previous committed tree (the current fiber tree) and the work-in-progress tree produced by the new render. The heuristic is what makes this fast enough to run on every state update: O(n) instead of the general tree-edit problem, which is O(n^3) for arbitrary trees.
Three rules do the work. First, elements of different types at the same position mean the whole subtree is torn down and rebuilt, so <div> becoming <span> discards every child below it. Second, elements of the same type are updated in place: React keeps the DOM node and fiber, and only patches props that changed. Third, lists are matched by key. Without stable keys, React matches children by index, and inserting at the front of a list rewrites every item.
Two things make this survive production. Keys must be stable identities from the data, not array indices, for any list that can reorder, insert or filter. And reconciliation is interruptible: since React 18's concurrent rendering, the work loop can yield to the browser mid-tree, so a slow diff of a large subtree does not block input, provided the work is marked as a transition or is otherwise non-urgent.
Walk-through trace
State: items = [A, B, C], rendered as <li key=...>. The user inserts X at the front.
| Keys in previous tree | Keys in next tree | Match by key | DOM work |
|---|---|---|---|
| A, B, C | X, A, B, C | A, B, C kept, X new | insert one <li> |
| A, B, C (no keys, index match) | X, A, B, C | index 0: A vs X, patch text; index 1: B vs A; ... | rewrite three, insert one |
With keys, React creates one fiber and one DOM node. Without them, it patches every existing node's text and props, then appends one more. Both produce the same final DOM. Only the first is cheap when the list is large and the children hold state, because state lives on the fiber and index matching hands the state of B to A.
Code: what a key bug looks like
// React 18, lists that reorder
items.map((item, i) => <Row key={i} item={item} />) // index key: row state sticks to the wrong item after a delete
items.map(item => <Row key={item.id} item={item} />) // stable id: state follows the itemFailure modes and how to detect them
- Remounts you did not expect. A component's state resets after a parent re-render. Cause: a type change higher up, or an inline component definition (
const Row = () => ...inside render), which gives a new type every render. Detect with React DevTools' "highlight updates" and by logging in auseEffectmount. - Index keys on reordering lists: input values and checkbox state jump to neighbouring rows. Detect by deleting the first row in a list that has local state.
- Expensive subtrees re-rendering on every parent update. React reconciles the whole subtree below any changed parent unless the child bails out.
React.memohelps only if props are referentially stable, so an inline object or callback prop defeats it. Profile with the React Profiler to see committed render counts and the reason for each render.
When not to lean on reconciliation
For very large lists (tens of thousands of rows), reconciliation cost is no longer the bottleneck; the fix is windowing (react-window or react-virtualized style), which keeps only visible rows mounted. Diffing a list of 50,000 items on each keystroke is a design problem, not a reconciliation problem.
State what you verified against: this answer assumes React 18 or later with the default reconciler, and the behaviour described for keys and element-type changes is in the React docs under "Preserving and Resetting State" and "Rendering Lists."
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Explain leader election and consensus (Raft) at a high level.
Reported in interview-rounds/content/interviews/mercado-libre-1.md at main · sumitsingh4411/interview-rounds
The 90-second answer
Raft gives a replicated log a single leader at any time, and only a majority of nodes can agree on what goes into that log. Every node is a follower, a candidate or the leader. Time is divided into terms, numbered integers that act as a logical clock. At most one leader exists per term, and a node that sees a higher term steps down.
The leader sends AppendEntries heartbeats to followers. Each follower holds an election timeout, randomised per node (the paper suggests 150 to 300 ms; etcd defaults to a 1000 ms election timeout with a 100 ms heartbeat). When a follower hears nothing for its timeout, it becomes a candidate, increments the term, votes for itself and sends RequestVote to the others. It wins with votes from a majority. Randomised timeouts make split votes rare and short, because one candidate usually times out first.
Writes go to the leader. It appends the entry locally, sends it to followers, and marks it committed once a majority has stored it. Only then does it apply the entry and reply to the client. That majority rule is what lets the cluster survive failures: 3 nodes tolerate 1 failure, 5 tolerate 2.
Why the election is safe
A candidate only gets a vote if its log is at least as up to date as the voter's, comparing last log term first, then last index. A node missing committed entries therefore cannot win, so a new leader always holds every committed entry.
Trace, 5 nodes (A to E), hypothetical
A is leader in term 3 with log index 7 committed on A, B and C. A crashes. D's timeout fires first at term 4. D sends RequestVote. B and C have a log ending at index 7 in term 3, D's log is at index 7 too, so they grant votes. D has 3 of 5 (its own plus B and C), wins, and sends heartbeats. E was partitioned and rejoins later; its higher-term heartbeat from D makes its own stale leadership impossible.
Failure modes to name
A leader cut off from the majority keeps believing it leads until it hears a higher term. If clients read from it, they get stale data. Fixes are ReadIndex (confirm leadership with a heartbeat round before serving the read) or leader leases, which depend on bounded clock drift and are riskier. Disk fsync on each commit sets the throughput ceiling, so batching matters. Membership changes done naively can allow two leaders in one term, so Raft uses joint consensus or single-server changes.
Where it sits
Etcd, Consul and CockroachDB build on Raft. Paxos gives the same guarantees with a harder-to-teach structure. Use Raft-backed coordination for metadata, leases and configuration, not for high-volume data: the write path pays a majority round trip on every commit.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Walk me through the architecture of a system you owned end to end.
Reported in interview-rounds/content/interviews/mercado-libre-1.md at main · sumitsingh4411/interview-rounds
The 90-second answer
I'd pick the system where I was the one paged, the one who wrote the design doc and the one who answered for its numbers. Before I describe it, I'd say what it did, who called it and what it had to hold: at Mercado Libre-scale traffic, the things that matter are peak order rate, the consistency needed between stock and payment, and the cost of a bad deploy. Then I'd walk the request path from edge to storage, and name the two decisions I'd defend hardest.
For example: a checkout-adjacent service that reserved stock for orders. Edge: the API gateway terminates TLS and enforces per-seller rate limits. Service: stateless Java/Spring Boot pods behind a load balancer, autoscaled on request latency rather than CPU. Data: PostgreSQL for reservations, with one row per (sku, warehouse) holding a version column, and Redis as a read-through cache for availability that is never trusted for the write path. Async: an outbox table written in the same transaction as the reservation, drained to Kafka by a relay, so the downstream fulfilment and notification consumers never miss an event and never need a distributed transaction with the service.
The two decisions I'd defend: the outbox over dual writes, and optimistic concurrency on the reservation row instead of pessimistic locks, because contention on a hot SKU was short and retries were cheap.
Trace of one request (hypothetical figures, labelled as such)
| Step | Where | Time (p50 / p99) |
|---|---|---|
| TLS + rate limit | gateway | 2 ms / 6 ms |
| Availability read | Redis | 1 ms / 4 ms |
Reserve: UPDATE with WHERE version = ? | Postgres | 6 ms / 35 ms |
| Outbox insert, same txn | Postgres | included above |
| Commit + respond | service | 1 ms / 3 ms |
A version conflict returns 409 and the client retries once with a fresh read. Under a flash sale on one SKU, I measured retry rate climbing past 20 percent around 300 concurrent buyers on that row, which is the point where I'd move that SKU to a sharded counter. I'd say that number is from my own load test, not a general rule.
Failure modes I'd name, and how I detected them
- Relay lag: outbox rows pile up when the relay falls behind. Detected by an alert on the age of the oldest unsent row, paged above 30 s.
- Cache drift: Redis availability diverges from Postgres after a missed invalidation. Detected by a reconciliation job comparing a sample of rows hourly, and by the reservation path always re-checking the row, so drift costs a wasted read, not an oversell.
- Connection exhaustion: each pod held a pool of 20 connections, and at 60 pods that is 1200 against a Postgres limit I had to keep under. Detected by pool wait time in the service metrics; I moved to PgBouncer in transaction mode after p99 wait went from 2 ms to 180 ms at saturation.
What I'd change now
I'd make the reservation TTL explicit in the API rather than a server default, because two consumers had assumed different values and that mismatch caused more incidents than any code bug.
The answer I'd close on is the one I can back with a number: the oversell rate was zero over the quarter I owned it, and I can say which decision protected that.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19What is backpressure and how do you handle it?
Reported in interview-rounds/content/interviews/mercado-libre-4.md at main · sumitsingh4411/interview-rounds
The 90-second answer
Backpressure is the signal a slow consumer sends upstream so a producer slows down instead of filling buffers until something dies. Without it, the queue between two stages grows without bound, memory climbs, latency goes from milliseconds to tens of seconds, and then the process is OOM-killed and every in-flight request is lost. I handle it at three layers: bound every queue, make the producer observe the consumer's capacity, and decide explicitly what to shed when capacity runs out. I'd ask first whether the path is in-process, service-to-service over HTTP, or a broker like Kafka, because the mechanism differs.
The key distinction is that a bounded buffer alone is not backpressure. A bounded buffer that silently drops or blocks forever just moves the failure. Backpressure means the slowness is propagated back to where the load originates, so the caller can wait, retry later, or reject.
| Layer | Mechanism | What the producer sees |
|---|---|---|
| In-process | bounded channel or queue, blocking put | blocks, or try_send fails |
| HTTP service | concurrency limit, 429 or 503 with Retry-After | explicit rejection |
| Kafka | consumer lag, producer max.block.ms and buffer limits | send blocks, then throws TimeoutException |
| Reactive streams | request(n) demand signal | producer emits only what was requested |
A worked trace. An order-events consumer processes at 500 msg/s. The producer emits 800 msg/s into an unbounded in-memory queue. After 60 s the queue holds 18,000 messages, and each new message waits about 36 s behind the backlog. With a bounded queue of 1,000 and a blocking put, the producer's throughput falls to the consumer's 500 msg/s within a second, the queue stays at 1,000 items, and worst-case queueing delay is 2 s. These figures are hypothetical, but the arithmetic is what you should be able to reproduce: delay equals queue depth divided by drain rate.
work := make(chan Event, 1000) // bounded
func produce(ctx context.Context, e Event) error {
select {
case work <- e:
return nil
case <-ctx.Done():
return ctx.Err() // caller learns the system is saturated
}
}The select with ctx.Done() matters. A blocking send with no deadline turns backpressure into a hung goroutine pool.
Choosing what to do when the bound is hit. Blocking is right when the producer is an internal pipeline and waiting is cheap. Rejecting with 429 or 503 plus Retry-After is right at a service edge, and clients must back off with jitter, not retry in a tight loop. Shedding is right when the data is lossy-tolerant: drop the oldest telemetry, coalesce duplicate price updates. Never shed a payment or order event silently. Those need a durable buffer such as Kafka, where the producer's lag is visible and you can throttle on it.
Failure modes to name. Retry storms: when rejections trigger immediate retries, load multiplies. Detect it by a spike in request rate paired with a flat success rate. Head-of-line blocking: one slow shard fills a shared pool and starves healthy traffic, so use per-tenant or per-route limits. Consumer lag growing without bound on Kafka: alert on lag in messages and in seconds, because a constant lag figure hides a rising trend. Timeouts that are longer than the caller's own timeout: work continues after the client has given up, wasting capacity the system needs.
I'd finish by saying how I'd verify it: a load test that pushes the producer to 1.6x consumer capacity and asserts that queue depth stays at the bound and p99 stays under the agreed budget, rather than watching the process survive.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Caching strategies: cache-aside, write-through, TTLs. Which would you use and why?
Reported in interview-rounds/content/interviews/mercado-libre-4.md at main · sumitsingh4411/interview-rounds
The 60-second answer
For a product listing read path I'd use cache-aside with a TTL on every key, and I'd invalidate on write rather than write through. The cache is an optimisation, so the database stays the source of truth and a cache outage costs latency, not correctness.
Assumptions: listing pages are read thousands of times more often than a listing changes; price and stock changes must show within seconds, not minutes; one Redis cluster per region.
Read path (cache-aside):
GET listing:{id}from Redis.- On a miss, load the row from the database and
SET listing:{id} <json> EX 300with jitter. - Write path: commit to the database, then
DEL listing:{id}.
Why delete instead of update on write: two writers racing to set the cache can leave a stale value behind. Delete makes the next reader repopulate from the committed row. A race still exists (a reader loads the old row, a writer commits and deletes, then the reader sets the old value), so the TTL bounds how long that stale value can live. That is why the TTL is not optional.
Write-through trade-off: every write pays a cache round trip, and the cache fills with keys nobody reads. It earns its cost when reads follow writes for the same key almost immediately. For a catalogue of 50 million listings where most are cold, I would not pick it.
| Strategy | Staleness bound | Extra write cost | Cache down | Use when |
|---|---|---|---|---|
| Cache-aside + TTL | TTL plus a short race window | none | DB load spikes | read-heavy, long cold tail |
| Write-through | near zero if every writer uses it | one cache round trip per write | writes fail or fall back to DB | hot keys, written then read |
| TTL only | full TTL | none | none | tolerant data such as counts or ratings |
Hypothetical arithmetic: 20k reads/s at a 95% hit ratio sends 1k misses/s to the database. At 99% it is 200/s, a fivefold cut in database load. That is why the hit ratio is the number I watch.
Failure modes and detection:
- Stampede: a hot key expires and 2,000 requests miss together. Use single-flight per key or a
SET lock:{id} 1 NX PX 2000guard, and jitter TTLs (300 s plus or minus 10%) so keys loaded together do not expire together. Detect with a spike in misses per key and DB QPS. - Stale price at checkout: never charge from the listing cache. Re-read price and stock server-side when the order is created.
- Cache unavailable: fall back to the database behind a rate limit, or the fallback itself takes the database down. Detect with miss ratio and database p99 on the read path.
- Staleness drift: sample served values against the database to measure real age, not the configured TTL.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21Find the minimum in a rotated sorted array.
Reported in interview-rounds/content/interviews/mercado-libre-4.md at main · sumitsingh4411/interview-rounds
The 60-second answer
I'd confirm three things first: the array is non-empty, the values are distinct, and it was produced by rotating an ascending array some k times, so it may be unrotated (k = 0 or n). With distinct values the answer is the single point where the sequence drops, found by binary search in O(log n) time and O(1) space.
The invariant: the minimum always lies in [lo, hi]. Compare nums[mid] with nums[hi]. If nums[mid] > nums[hi], the rotation break is to the right of mid, so the minimum is in (mid, hi]. Otherwise mid sits in the sorted tail that ends at hi, so mid itself could be the minimum and must stay in range.
# Python 3.12
def find_min(nums: list[int]) -> int:
lo, hi = 0, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
if nums[mid] > nums[hi]:
lo = mid + 1
else:
hi = mid
return nums[lo]Trace on [3, 4, 5, 1, 2]:
| step | lo | hi | mid | nums[mid] | nums[hi] | action |
|---|---|---|---|---|---|---|
| 1 | 0 | 4 | 2 | 5 | 2 | 5 > 2, lo = 3 |
| 2 | 3 | 4 | 3 | 1 | 2 | 1 is not > 2, hi = 3 |
lo == hi == 3, return 1. Two comparisons for five elements.
Why compare with hi, not lo. Comparing with lo cannot tell an unrotated range from a rotated one when mid sits in the left run. Comparing with hi always has the answer on a known side.
Duplicates. Once values can repeat, nums[mid] == nums[hi] no longer proves the minimum is not at mid or to its left. The safe move is hi -= 1, which drops one candidate that is equal to a value still in range. Worst case becomes O(n), for example [1, 1, 1, 1, 0, 1, 1], where the duplicate run can hide the drop. If the interviewer adds duplicates, say so before coding and state the O(n) worst case.
Failure modes to name.
- Off-by-one on
hi: usingwhile lo <= hiwithhi = mid - 1returns the wrong slot unless the return value is handled, and it can loop forever with theelsebranch. Thelo < hiform withhi = midavoids this. - Empty input:
len(nums) - 1is -1 andnums[0]raises. Guard it or document the precondition. - An unrotated array: the loop still returns
nums[0], which is correct, so there is no special case.
Testing. Run unrotated input, single element, two elements, every rotation of a small array, and the minimum at each end. Those cover the boundaries where the hi comparison matters.
Follow-up I'd expect. Find the index instead of the value: return lo rather than nums[lo]. Search for a target in the rotated array: find the pivot, then run a standard binary search on the correct half, which is still O(log n).
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-22Describe a challenging technical decision you made, why you made it, and what the outcome was.
Reported in Preguntas de entrevista para Software Engineer en Mercado Libre
The 90-second answer
I'll pick a decision where I had to choose between two reasonable options with incomplete data, and where I was wrong about one assumption. Give me a sec to set context: the situation, the options, the call, and what I'd change.
The situation I'd describe: a payments-adjacent service at our scale, where a read path was hitting a shared Postgres table that the order-status team also wrote to. p99 on the read endpoint climbed from about 60 ms to 400 ms during the evening peak. Two options were on the table. Option A: add read replicas and route reads there, accepting replication lag of typically 100 to 300 ms. Option B: build a dedicated projection (a denormalized table fed from the order event stream) and serve reads from it, which costs a new consumer, a backfill, and an owner for the projection's correctness.
I chose B, and the reason was the consistency requirement, not performance. The product needed the buyer to see a cancellation within a second of pressing it. Replicas with 300 ms lag met that on paper, but failover and lag spikes during deploys pushed lag past 5 s on bad days, and I had no way to bound it from the application side. A projection let me set the freshness budget explicitly and alert on consumer lag.
What I assumed and got wrong: I assumed the event stream was complete. It wasn't. Two legacy write paths updated the table directly without emitting events, so the projection drifted by roughly 0.3% of rows in the first week. I caught it with a nightly reconciliation query that compared counts and sampled 1,000 rows by id, and then I fixed the write paths rather than papering over the drift in the consumer.
Outcome, with numbers
| Metric | Before | After |
|---|---|---|
| p99 read latency, peak | 400 ms | 45 ms |
| Read load on primary | ~3,800 qps | ~200 qps |
| Freshness budget (p99 event-to-visible) | unbounded | 800 ms, alerted above 2 s |
The honest cost: we now run one more service, and the projection's schema change process is slower than it was. I'd still make the call, but I'd have written the reconciliation job on day one instead of week one.
What I'd tell an interviewer I'd do differently
Before committing, I would have listed every write path to the table and checked each emitted an event. That check takes an hour and would have removed the drift entirely. The decision was sound; my inventory of the system was not.
Follow-ups I'd expect
Why not cache instead? A cache with invalidation would have been cheaper, but invalidation was the exact bug class we were trying to escape, and cache misses on the peak keyset would still have hit the primary. Why not both? We did add a short-TTL cache in front of the projection later, for the product page only, once the projection was stable.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: