Skip to content
Tech Interview Prep

Real Interview Questions for the Software Engineer at América Móvil

New

Interview Q&A

25 questions · Flow follows Relevance until this set has a learning order.

Q&A-1Tell me about a time you had to handle a critical production incident affecting many users. What did you do, and what was the outcome?

Reported in Senior Software Engineer – Backend (BSS/OSS) interview at America Movil

The 90-second answer

At a telecom operator I worked on the prepaid charging path, the service that checks balance and deducts for calls, data and recharges. A deploy at 19:40 raised the timeout on the balance service from 300 ms to 2 s to absorb a slow database replica. That change let slow queries hold database connections far longer. Within 20 minutes the connection pool saturated, balance checks timed out, and customers in two regions could not recharge or start calls. I was on call. I confirmed the blast radius from dashboards, froze further deploys, rolled back the config, and drained the pool so queued requests could complete. Service recovered in 47 minutes. We refunded or re-credited every failed recharge, verified no customer was double charged, and shipped a fix that capped timeouts per dependency and added pool saturation alerts.

What I did, in order

First I separated signal from noise. Error rate on POST /recharges had gone from 0.2% to 38%, p99 latency from 180 ms to 2,000 ms, and active database connections had pinned at the pool limit of 50 per pod. Support tickets matched the same regions and the same minute. That ruled out a single bad node.

I then checked the last change. The config diff was the only change in the window, and the timing lined up with the replica lag metric. I did not try to tune the pool live. I rolled back the timeout to 300 ms, restarted the pods to clear stuck connections, and watched the queue drain. Restarting mattered because rollback alone left connections held by queries already in flight.

While recovery ran, I pulled the list of affected transactions from the recharge ledger so finance could re-credit them without manual tickets.

TimeSignalAction
19:40Config deploy, timeout 300 ms to 2 sNoticed in change log after alert
20:02Error rate 38%, pool at 50/50Declared incident, froze deploys
20:11Replica lag 12 s, queue growingRolled back config, restarted pods
20:27Error rate below 1%, queue drainingMonitored, opened ledger query
20:47Error rate back to 0.2%Closed incident, started re-credit job
Alert: recharge errors 38% Confirm scope by region and service Check last deploy and config diff Freeze deploys and roll back Restart pods to clear stuck connections Verify error rate and queue drain Re-credit failed recharges from ledger

Outcome and the check that mattered

About 180,000 customers in the two regions were affected, with roughly 12,000 failed recharge attempts. Because recharges carried an idempotency key, retries during the outage did not create duplicate credits. I verified that with this query before finance ran the re-credit job:

SQL
-- PostgreSQL, run against the recharge ledger after recovery
SELECT idempotency_key, COUNT(*) AS attempts, COUNT(DISTINCT credit_id) AS credits
FROM recharges
WHERE created_at BETWEEN '2024-06-12 19:40' AND '2024-06-12 20:47'
GROUP BY idempotency_key
HAVING COUNT(DISTINCT credit_id) > 1;

It returned zero rows. Every failed attempt had zero credits, so re-crediting by idempotency key was safe and auditable. No customer was double charged, and the re-credit job completed the same night with a reconciliation report finance signed off.

What changed after

We added a hard cap so a timeout change cannot exceed the pool budget, an alert on pool saturation above 80% for 2 minutes, and a load test that replays peak recharge traffic against a degraded replica. The follow-up also moved the timeout into a per-dependency config with a circuit breaker, so a slow replica now sheds load instead of consuming every connection. The next deploy of the same replica fix went out behind a flag at 5% of traffic, with automatic rollback if p99 crossed 500 ms.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2Design a high-availability system to track mobile data usage in near real time for millions of subscribers across multiple Latin American countries, supporting querying current usage and triggering threshold alerts?

Reported in Senior Software Engineer – Backend (BSS/OSS) interview at America Movil

The 90-second answer

I would split this into ingestion, aggregation, serving and alerting, and keep country data residency as a hard constraint from the start. América Móvil operates in 20-plus countries, so a single global write path would fail on latency, regulation and blast radius. I would run a regional cell per country group, for example Mexico, Brazil, Colombia and the Southern Cone, each with its own Kafka cluster and serving store, and replicate only aggregated, anonymised metrics cross-region for operations.

The source is not the handset. It is the packet gateway and charging system: GGSN/PGW session records and CDRs, plus prepaid charging events from the IN. Those arrive as a stream of usage deltas, each with a stable event id such as imsi + gateway_id + session_seq. The gateway is the deduplication point. Without it, a retried CDR inflates a subscriber's usage and triggers a false alert.

PGW and charging events per country Kafka per region, partitioned by IMSI hash Stream aggregation, 1 min windows ScyllaDB current usage by subscriber Redis cache for hot queries Query API, regional Threshold engine Notification and BSS hooks

Aggregation and serving

Assume, as a worked example, 30 million active data subscribers across the group and a peak of 60,000 usage events per second at the busiest hour. That is small for Kafka if partitioned by IMSI hash, but it is too much for a relational row lock per event. I would aggregate in Flink or Kafka Streams into 1-minute tumbling windows per subscriber, then upsert the window total into ScyllaDB keyed by (country, imsi, cycle_start). ScyllaDB fits because the access pattern is a point lookup by subscriber and a range scan for the current billing cycle, and it tolerates multi-AZ writes without a primary election pause.

Current usage is then a sum over at most 43,200 one-minute rows per cycle, which is still too many for a hot API. So the aggregator also maintains a materialised current_cycle_total row updated in the same window commit, and Redis caches the top 5 percent of subscribers by query volume, for example customers checking usage in the app after a large download. Cache TTL is 30 seconds. A stale read of 30 seconds is acceptable for usage display and is stated in the API contract as as_of timestamp.

PathStoreConsistencyFailure behaviour
GET /subscribers/{imsi}/usageScyllaDB, Redis in frontEventual, as_of returnedRedis miss falls through to ScyllaDB
Threshold checkStream processor stateExactly-once per window commitReplay from Kafka offset on restart
Billing cycle closeScyllaDB batch jobStrong per partitionRe-runnable, idempotent by cycle key

Threshold alerts without alert storms

Thresholds are per plan, not global: 80 percent and 100 percent of the included allowance, plus a hard cap for prepaid. The stream processor keeps per-subscriber state: total_so_far, last_alert_level, last_alert_at. When a window pushes the total across a level, it emits an alert event to a separate topic and records the level in the same transaction as the window commit. Hysteresis and cooldown prevent flapping: once the 80 percent alert fires, the next alert requires crossing 100 percent or 4 hours to pass, whichever comes first. That rule is what stops a subscriber hovering at 79 to 81 percent from generating an alert every minute.

Python
# Python 3.12, checked against Flink 1.18 PyFlink semantics for state
def on_window(imsi, window_total, state, plan):
    state["total"] += window_total
    for level in (0.8, 1.0):
        threshold = plan.allowance_bytes * level
        if state["total"] >= threshold and state["alerted"] < level:
            state["alerted"] = level
            emit_alert(imsi, level, state["total"], state["as_of"])
            break

Delivery to SMS, push and the BSS is via an outbox table in the alert service. The processor writes the alert and an outbox row atomically, and a relay publishes to the notification gateway with retries. If the gateway is down, alerts queue instead of being lost, and the API can still report that an alert is pending.

High availability

Each region runs in three availability zones. Kafka replication factor 3, min in-sync replicas 2, so a zone loss does not stop ingestion. ScyllaDB replication factor 3 across zones, with reads served from the local zone and writes quorum-based. The query API is stateless behind a regional load balancer, so a zone loss reduces capacity by a third and the autoscaler replaces it. Cross-region, I would not do active-active writes for usage, because two regions accepting the same IMSI would need conflict resolution on every window. Instead, each country has one primary region, and a secondary region in another country replicates the ScyllaDB data asynchronously for disaster recovery with a stated RPO of 5 minutes. Failover is a DNS and routing change plus promotion of the replica, rehearsed quarterly, because an unrehearsed failover is a guess.

The failure modes I would name in the interview are duplicate CDRs from a gateway retry, a hot IMSI partition when a stadium crowd shares a cell, and clock skew between gateways making window boundaries disagree. Duplicates are handled by the event id dedup store with a 48 hour TTL. Hot partitions are handled by salting the Kafka key with a window bucket for aggregation while keeping the serving key unsalted. Clock skew is handled by using gateway event time with a 2 minute allowed lateness, and late events beyond that go to a correction topic that adjusts the current total and marks the cycle as amended for billing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3Given a list of CDR-like records with subscriberId, startTime, endTime, and callType, implement a Java method that returns a map from subscriberId to total call duration in seconds, considering only VOICE calls?

Reported in Senior Software Engineer – Backend (BSS/OSS) interview at America Movil

The 90-second answer

Assume startTime and endTime are epoch seconds, duration is endTime - startTime per record, and overlapping records for the same subscriber are summed as recorded. That last point matters for CDRs. If the feed can contain duplicate or overlapping legs for one call, summing double counts and you would need interval merging first. I would state that assumption before coding.

Filter to VOICE only, skip or reject malformed rows explicitly, and accumulate in a HashMap<String, Long> with merge. One pass, O(n) time, O(k) space for k distinct subscribers.

Java
// Java 17
import java.util.*;

enum CallType { VOICE, DATA, SMS }

record Cdr(String subscriberId, long startTime, long endTime, CallType callType) {}

final class CdrTotals {
    Map<String, Long> totalVoiceDurationSeconds(List<Cdr> records) {
        if (records == null || records.isEmpty()) {
            return Map.of();
        }
        Map<String, Long> totals = new HashMap<>();
        for (Cdr r : records) {
            if (r == null || r.callType() != CallType.VOICE) {
                continue;
            }
            if (r.subscriberId() == null || r.subscriberId().isBlank()) {
                throw new IllegalArgumentException("CDR missing subscriberId: " + r);
            }
            long duration = r.endTime() - r.startTime();
            if (duration < 0) {
                throw new IllegalArgumentException("CDR endTime before startTime: " + r);
            }
            // addExact fails loudly on overflow instead of wrapping to a negative billable total
            totals.merge(r.subscriberId(), duration, Math::addExact);
        }
        return totals;
    }
}

Worked trace

RecordsubscriberIdstartendcallTypeActionRunning total
1sub-110001060VOICEadd 60sub-1 = 60
2sub-120002030DATAskipsub-1 = 60
3sub-210001120VOICEadd 120sub-2 = 120
4sub-130003015VOICEadd 15sub-1 = 75
5sub-240003990VOICEthrow, negative duration-

Result for records 1 to 4: {sub-1=75, sub-2=120}.

Decisions an interviewer will probe

Null handling is a contract choice, not a detail. Returning Map.of() for a null list is convenient for a batch job that treats no input as no usage. Throwing on a blank subscriberId or negative duration is deliberate. In billing, silently dropping a VOICE record underbills and the error surfaces weeks later in reconciliation. Failing the batch points at the corrupt record, which the operator can quarantine and replay. If the caller prefers quarantine over failure, collect rejected records in a separate list and return both, rather than mixing the two policies inside the loop.

Overflow: a single call duration fits easily in a long, but a subscriber total over years of CDRs is still far from Long.MAX_VALUE. addExact costs almost nothing here and turns a theoretical wrap into an explicit failure. That is the right trade for money adjacent code.

Return type: Map<String, Long> matches the question. If the caller needs deterministic output for a file or a test, wrap the result in a TreeMap at the boundary or sort when serialising. Do not pay for sorting inside the aggregation.

When this shape breaks

A List<Cdr> already in memory is fine for a test or a small extract. For a nightly CDR file with tens of millions of rows, loading the list first is the failure mode. Memory grows with the input, and the job dies on heap before it finishes. The fix is to stream: read line by line, parse, and feed the same merge logic, or push the aggregation into the store with GROUP BY subscriber_id, SUM(end_time - start_time) WHERE call_type = 'VOICE'. The accumulation logic stays identical. Only the source changes.

Overlapping intervals are the other trap. Two records for the same call, one from the switch and one from a mediation retry, sum to twice the real duration. Detect it by checking for duplicate (subscriberId, startTime, endTime) keys upstream, or sort per subscriber and merge intervals before summing. I would ask which guarantee the feed gives before choosing. If duplicates are possible, dedupe on a CDR id field if one exists. Interval merging without an id is a guess and can underbill a subscriber who genuinely made two overlapping calls on different lines.

Complexity stays O(n) either way. The interview answer is the single pass plus the stated assumptions about duplicates, malformed rows, and input size.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-4You receive a continuous stream of call detail records (CDRs) from network elements. Design and implement a service in Java that aggregates total call duration per subscriber for a given day, and how would your approach change as volume grows to tens of millions per day?

Reported in Senior Software Engineer – Backend (BSS/OSS) interview at America Movil

The 90-second answer

I would treat this as an idempotent stream aggregation, not a database query over raw CDR files. Each CDR carries a globally unique cdrId, subscriberId, startTime, and durationSeconds. I aggregate in memory keyed by (day, subscriberId), deduplicate on cdrId before adding, and flush periodically to a store keyed the same way so a restart or replay does not double count. For a single day and a few million records that fits in one JVM. At tens of millions per day I partition by subscriber hash across Kafka partitions and workers, then merge partial totals.

Assumptions I would state first: the day is defined in the subscriber's home timezone, for América Móvil traffic that is typically America/Mexico_City for Mexican subscribers, and a call belongs to the day of its start time. Late CDRs arriving after midnight still update the day they started, not the arrival day. Duration is taken from the network element as authoritative, I do not recompute it from answer and release timestamps unless the feed is known to omit it.

Java
// Java 21, checked against java.util.concurrent only
public record Cdr(String cdrId, String subscriberId,
                  Instant startTime, long durationSeconds) {}

public final class DailyAggregator {
    private final ZoneId zone;
    private final ConcurrentHashMap<Key, LongAdder> totals = new ConcurrentHashMap<>();
    private final Set<String> seen = ConcurrentHashMap.newKeySet(); // bounded in prod, see below

    private record Key(LocalDate day, String subscriberId) {}

    public DailyAggregator(ZoneId zone) { this.zone = zone; }

    public void onCdr(Cdr cdr) {
        if (!seen.add(cdr.cdrId())) return; // duplicate delivery from the mediation feed
        LocalDate day = LocalDate.ofInstant(cdr.startTime(), zone);
        totals.computeIfAbsent(new Key(day, cdr.subscriberId()), k -> new LongAdder())
              .add(cdr.durationSeconds());
    }

    public Map<Key, Long> snapshot() {
        Map<Key, Long> out = new HashMap<>();
        totals.forEach((k, v) -> out.put(k, v.sum()));
        return out;
    }
}

LongAdder matters here. A plain Long in a ConcurrentHashMap loses updates under concurrent adds for the same subscriber, and a single hot subscriber on a busy cell site can be updated hundreds of times per second. seen as an unbounded set is the weak point in this sketch. In production I would not keep it forever. I would deduplicate in the stream layer with a bounded window, for example a Kafka Streams or Flink state store with a 48 hour retention, or persist cdrId in the sink with a unique constraint and let the database reject the replay.

Worked trace for one subscriber, sub_991, on 2026-03-14 in America/Mexico_City:

Time (local)cdrIdDuration (s)Running total (s)Note
08:02:11c1120120first call
08:02:11c1120120duplicate delivery, dropped by seen
09:40:03c245165
23:59:40c3300465starts before midnight, counts for 14 Mar
00:01:10 next dayc460465 for 14 Mar, 60 for 15 Marnew day key
02:00:00 next dayc590555 for 14 Marlate arrival, updates the original day

That last row is the case interviewers probe. If you bucket by arrival time or by processing date, late CDRs silently land on the wrong day and the total for 14 Mar never reconciles with the mediation system.

Scaling to tens of millions per day

The arithmetic is reassuring. 30 million CDRs per day is about 350 per second on average. Even with a 10x peak factor that is 3,500 per second, which a single well tuned JVM handles easily for in memory adds. The problem at that volume is not CPU, it is state size, replay, and correctness across restarts.

Network elements Mediation feed Kafka topic, partitioned by subscriberId Aggregator worker 1 Aggregator worker 2 Aggregator worker 3 Totals store, upsert by day and subscriber

Partitioning by subscriberId keeps all CDRs for one subscriber on one worker, so partial totals never need cross worker merging during the day. The sink does an upsert: INSERT ... ON CONFLICT (day, subscriber_id) DO UPDATE SET total_seconds = total_seconds + EXCLUDED.delta. Workers flush every few seconds rather than per record, which turns 3,500 upserts per second into a few hundred batched writes.

ApproachWhen it worksWhere it breaks
Single JVM, ConcurrentHashMapUp to roughly 5 to 10 million CDRs per day, one regionRestart loses in memory state, seen set grows without bound, no replay safety
Kafka plus partitioned workers, upsert sinkTens of millions per day, multi regionNeeds careful handling of rebalances and late data windows
Flink or Spark Streaming with event timeHundreds of millions per day, complex windowsOperational cost is high for a simple sum, overkill if the only query is daily totals

I would pick the middle row for América Móvil scale. Flink earns its keep when you need event time windows, joins against rating tables, or exactly once semantics across multiple sinks. For a single daily sum it adds a cluster to operate for a problem Kafka partitioning already solves.

Failure modes I would name

Duplicate CDRs from mediation retries are the most common. Deduplication on cdrId handles them, but only if the feed actually supplies a stable id. If it does not, I would fall back to a composite key of subscriber, start time, dialled number, and duration, and accept a small false duplicate rate rather than double counting.

Clock skew between network elements can push a call across midnight in the wrong direction. I would monitor the distribution of CDRs near the day boundary and alert if the count in the 23:55 to 00:05 window deviates sharply from the same window on prior days.

A hot subscriber, such as a corporate PBX trunk, can concentrate updates on one key. LongAdder spreads contention across cells internally, and partitioning by subscriber means one hot key only slows one worker. If a single subscriber ever exceeded what one partition could absorb, I would split by a secondary hash and merge at flush time.

Finally, the query path. GET /subscribers/{id}/daily-usage?day=2026-03-14 reads from the totals store, never from raw CDRs. That keeps the read at one indexed lookup even when the raw feed is 30 million rows a day, and it gives billing a stable number to reconcile against once the day closes and late arrivals taper off.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5Describe a situation where you had conflicting priorities with another team (for example, a business or operations team). How did you handle it and what was the impact?

Reported in Senior Software Engineer – Backend (BSS/OSS) interview at America Movil

The 90-second answer

I would start by naming the conflict in numbers, not in team preferences. In my last BSS role, the business team wanted a new prepaid eSIM activation flow live for a World Cup promotion, and operations wanted a code freeze while we migrated rating tables for a new tariff. Both requests were legitimate. The promotion had a fixed date and a revenue target. The migration touched the same activation service, and a defect there would break activations for existing customers, not just the new campaign.

I did not pick a side. I asked both teams to score the options against the same criteria: revenue at risk, customers affected if it failed, and the cost of delay. That turned a priority argument into a decision we could defend.

The situation

We had six backend engineers for the quarter. The promotion needed four of them for five weeks to build eSIM profile provisioning, a new eligibility check, and a self-service activation API. The tariff migration needed the same engineers for three weeks, plus two weeks of parallel running and reconciliation. Running both in the same release window meant either the promotion slipped by six weeks, past the campaign, or the migration went live without parallel running.

Operations had a concrete failure mode. During the previous migration, a rating mismatch caused 1.8% of prepaid top-ups to be charged at the old rate. Finance caught it after three days. With the promotion traffic expected to be roughly 3x normal activations, the same error rate would have meant thousands of incorrect charges during the highest visibility period of the year.

Business had a concrete number too. The campaign forecast, which I will treat as hypothetical for this example, was 400,000 new activations in four weeks at an average first month revenue of MXN 180 per line. Missing the window did not lose all of that, but the forecast assumed the promotion price point. A six week delay meant launching at the standard price, which the marketing team estimated would cut conversion by about a third.

What I did

I proposed a phased release and put the trade-off in a table both teams signed off on.

OptionBusiness outcomeOperations riskEngineering cost
Promotion first, migration afterCampaign launches on dateMigration rushed, no parallel runHigh rework, two rating paths to maintain
Migration first, promotion afterCampaign misses window, lower conversionParallel run completed, reconciliation cleanLow rework
Phased: promotion on old rating path, migration behind feature flagCampaign launches, migration follows 4 weeks laterOld path frozen, no schema change during campaignMedium, flag and dual read for 4 weeks

The phased option won because it separated the two changes. We shipped the eSIM flow against the existing rating tables, with the new tariff code paths disabled by flag. We added a daily reconciliation job that compared activation counts and charged amounts between the activation service and the billing system, alerting if the mismatch exceeded 0.1%. Operations got their freeze on the rating schema. Business got their date.

Yes No Conflict: same engineers, same window Score revenue at risk and failure blast radius Can changes be separated by flag or schema? Phase the release, freeze shared schema Sequence by customer impact, escalate with numbers Reconcile daily during campaign

Impact

The promotion launched on the planned date. Activation success stayed at 99.2%, in line with the previous quarter, and the reconciliation job caught one pricing discrepancy on day two affecting 47 activations, which we corrected before settlement. The migration then ran with a four week parallel period. We found two mapping errors in that period, both fixed before cutover, and the cutover itself had zero incorrect charges in the first week.

The cost was real. Maintaining the flag and the dual read added about three weeks of engineering work, and the team worked one weekend during the campaign to handle a spike in activation failures from a partner eSIM vendor. I would not present the phased option as free. It was cheaper than a rollback or a finance correction after a bad migration, and it gave both teams something measurable to check instead of a promise.

What I took from it, and what I now propose at planning time, is a shared priority sheet before sprint allocation: each request lists the date it loses value, the number of customers affected if it fails, and whether it touches a shared schema or service. When two teams want the same engineers, we fill that sheet in together. It does not remove the conflict. It makes the decision auditable when the next conflict arrives.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6Design a high-availability, low-latency prepaid charging service handling tens of thousands of requests per second across multiple Latin American countries. How would you ensure balance consistency, handle retries, and meet data residency requirements?

Reported in Software Engineer II – Backend (Telecom BSS/OSS) interview at America Movil

The 90-second answer

I would not build one global balance store. Prepaid charging is a per-subscriber ledger, so I would shard by subscriberId and make exactly one shard the writer for that subscriber at any time. That gives strong consistency where it matters, without paying for global consensus on every call. Each country runs its own cell, with its own database and cache, so a failure in Brazil does not take down Mexico and subscriber data never leaves the country it was collected in. Cross-country traffic is only aggregated reporting, replicated asynchronously and stripped of identifiers.

For latency, the hot path stays in memory. A regional edge tier holds the current balance and active reservations, backed by a partitioned relational store for durability. A reserve request checks the in-memory balance, writes a reservation record, and returns in tens of milliseconds. Settlement and CDR rating happen off the hot path.

Retries are handled with idempotency, not hope. Every charging request carries a client-generated requestId, typically the Diameter Session-Id plus Request-Number, or an HTTP Idempotency-Key from the network element. The first attempt stores the outcome. A retry returns the stored outcome instead of debiting twice.

Network element / switch Regional edge: auth + cache Subscriber shard: single writer Regional DB: ledger + reservations Dedup table: requestId to outcome Async: rating, CDR, billing Aggregated reporting, no PII

Sizing and sharding

Assume 30,000 charging requests per second at peak across the group, which is the order of magnitude in the question. If a shard comfortably handles about 2,000 writes per second with headroom for failover, I need at least 15 shards for writes, so I would start with 32 shards per large country and fewer for smaller ones. Sharding is by hash of subscriberId, and the shard map is stored in a small config service, not derived from a global hash ring that would move subscribers during a resize.

Each shard is a primary plus two in-country replicas. Failover promotes a replica inside the same country and region. That keeps data residency intact and keeps the failover time bounded. I would not do active-active writes for the same subscriber across countries. If a subscriber roams, the home country shard remains the writer and the visited network calls it over a private link. That is slower than a local write, but it prevents two countries debiting the same balance.

Balance consistency

The invariant is simple: balance = granted - reserved - settled. A reserve operation is a single atomic transaction on the shard: check balance, insert a reservation row with an expiry, decrement available balance, commit. If the commit succeeds, the reservation exists. If it fails, no balance moved.

Java
// Java 17, inside the shard service. reserve() runs in one DB transaction.
public ReserveResult reserve(String subscriberId, String requestId,
                            long amountCents, long ttlSeconds) {
    return tx.execute(status -> {
        var prior = dedup.find(requestId);
        if (prior != null) return prior.result(); // replay, do not debit again

        var acct = accounts.lockBySubscriberId(subscriberId); // SELECT ... FOR UPDATE
        if (acct.availableCents() < amountCents) {
            var denied = ReserveResult.denied(acct.availableCents());
            dedup.save(requestId, denied);
            return denied;
        }
        reservations.insert(subscriberId, requestId, amountCents,
                            Instant.now().plusSeconds(ttlSeconds));
        accounts.decrementAvailable(subscriberId, amountCents);
        var granted = ReserveResult.granted(acct.availableCents() - amountCents);
        dedup.save(requestId, granted);
        return granted;
    });
}

The in-memory cache is a read accelerator, not the source of truth. It is invalidated on every write and rebuilt from the shard on a miss. If the cache and the database disagree, the database wins and the cache entry is dropped. That choice costs a few milliseconds on a miss and avoids the classic failure where a stale cache grants credit the account does not have.

Reservations expire. A voice call that never sends an update or a final debit leaves its reservation to lapse after, say, 300 seconds, and the amount returns to available balance. Expiry is a sweeper job per shard, not a background task that scans all shards from one place.

Retries and duplicate debits

AttemptWhat the shard seesResponseBalance effect
1requestId=abc-17, no dedup rowgranted, remaining=420 cents-100 cents reserved
2, same keydedup row foundsame granted body, replayednone
3, new keyno dedup rowgranted, remaining=320 cents-100 cents reserved

The dedup row is written in the same transaction as the balance change, so there is no window where money moved but the outcome was not recorded. Dedup rows are kept for at least 24 hours, longer than any client retry window, then archived. A retry with a different requestId is treated as a new request, which is correct: the client asked for a new reservation.

Timeouts need care. If the network element times out after 2 seconds and retries, it must reuse the same requestId. I would state that in the interface contract and test it with a chaos drill that kills the connection after the server commits but before the response arrives. That is the case that produces double debits in systems without dedup.

Latency budget

A realistic budget for a reserve call inside the country: 5 ms network to the edge, 10 ms cache lookup, 15 ms shard transaction, 5 ms response. That is about 35 ms end to end, with p99 under 100 ms even on a cache miss. The expensive work, rating the CDR, applying taxes, and writing the invoice record, runs asynchronously from the CDR stream. If rating falls behind, charging still works and the CDR queue depth becomes the alert, not a failed call.

Data residency and regulation

Each country cell stores subscriber identifiers, balances, and CDRs only inside that country, in at least two availability zones. Replication to another country is not used for the ledger. For group reporting, I would export daily aggregates by country, product, and hour, with no subscriber identifiers. That satisfies group finance without moving personal data across borders.

Access is role based and logged. Every balance adjustment, manual credit, and reservation override writes an audit row with operator, reason code, and before and after amounts. Retention follows local rules, which differ by country, so retention is a per-cell configuration rather than a global constant. Where local law requires data to stay in country for a fixed period, the archive tier is in country too.

Failure modes I would name in the interview

Shard failover during a reserve: the transaction either commits on the old primary or the client gets an error and retries with the same requestId against the new primary. Split brain is prevented by fencing the old primary before the new one accepts writes. Cache stampede after a shard restart: requests fall through to the database, which is sized for it, and the cache refills gradually. Clock skew on reservation expiry: expiry uses database time on the shard, not client time, so a client with a wrong clock cannot extend a reservation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7Explain how you would design and implement a RESTful endpoint in a Spring Boot microservice to retrieve total call duration for a subscriber within a date range, using Oracle, and discuss annotations, transaction handling, and performance?

Reported in Software Engineer II – Backend (Telecom BSS/OSS) interview at America Movil

The 90-second answer

I would expose GET /subscribers/{subscriberId}/call-duration?from=2025-01-01&to=2025-01-31 and return the summed duration in seconds, plus the window I actually queried. The controller only validates input. A service method marked read-only does the aggregation, and a Spring Data repository runs one Oracle query. No transaction writes anything, so the transaction exists to give the read a consistent snapshot and a bounded connection lifetime.

Java
// Spring Boot 3.3, Java 21, Oracle Database 19c
@RestController
@RequestMapping("/subscribers/{subscriberId}")
public class CallDurationController {

    private final CallDurationService service;

    public CallDurationController(CallDurationService service) {
        this.service = service;
    }

    @GetMapping("/call-duration")
    public CallDurationResponse total(
            @PathVariable String subscriberId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate from,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate to) {
        if (to.isBefore(from)) {
            throw new BadRequestException("to must not be before from");
        }
        if (ChronoUnit.DAYS.between(from, to) > 92) {
            throw new BadRequestException("window exceeds 92 days");
        }
        return service.total(subscriberId, from, to);
    }
}

@Service
public class CallDurationService {

    private final CdrRepository repository;

    public CallDurationService(CdrRepository repository) {
        this.repository = repository;
    }

    @Transactional(readOnly = true, timeout = 5)
    public CallDurationResponse total(String subscriberId, LocalDate from, LocalDate to) {
        LocalDateTime start = from.atStartOfDay();
        LocalDateTime endExclusive = to.plusDays(1).atStartOfDay();
        long seconds = repository.sumDuration(subscriberId, start, endExclusive)
                .orElse(0L);
        return new CallDurationResponse(subscriberId, from, to, seconds);
    }
}

@Repository
public interface CdrRepository extends JpaRepository<Cdr, Long> {

    @Query("""
        select coalesce(sum(c.durationSec), 0)
        from Cdr c
        where c.subscriberId = :subscriberId
          and c.callStart >= :start
          and c.callStart < :endExclusive
        """)
    Optional<Long> sumDuration(
            @Param("subscriberId") String subscriberId,
            @Param("start") LocalDateTime start,
            @Param("endExclusive") LocalDateTime endExclusive);
}

Note the half-open window. Comparing callStart < nextDay keeps the predicate sargable. BETWEEN on a date column invites an off-by-one when call_start carries a time component, which CDR timestamps always do.

Why the query is fast enough, and when it stops being

A CDR table for a large operator holds billions of rows. The aggregation is only cheap if Oracle can prune to one subscriber and a narrow time slice before summing. The index I would insist on is:

SQL
create index idx_cdr_sub_start
    on cdr (subscriber_id, call_start, duration_sec);

duration_sec as a stored column matters. Computing (call_end - call_start) * 86400 per row forces Oracle to evaluate an expression for every row in the slice. With the stored column, the plan is an index range scan plus a small in-memory sum, and Oracle can satisfy the sum from the index without visiting the table for the duration value. For a subscriber with, say, 3,000 calls in a month, that is a few milliseconds. For a 92-day window on a heavy roamer it can still be tens of thousands of rows, which is why I cap the window at 92 days and set a 5 second transaction timeout.

If the table is range-partitioned by month on call_start, which most BSS CDR tables are, partition pruning does the rest. The predicate on call_start eliminates every partition outside the window before the index is even touched. Without partitioning, the same index still works, but buffer cache pressure grows as the table ages.

Design choiceEffect on this queryWhen I would change it
Stored duration_secIndex-only aggregation, no per-row arithmeticIf rating rules change duration after the fact, keep raw start and end and compute in a nightly rollup instead
Composite index (subscriber_id, call_start, duration_sec)Range scan bounded by both predicatesIf most queries are by date alone across all subscribers, add a separate date-first index or a materialized view
Monthly range partitionsPrunes partitions outside the windowIf CDR retention is under 90 days, partitioning adds operational cost for little gain
92-day window capBounds worst-case rows scanned per requestRaise it only with a pre-aggregated daily summary table behind the endpoint

Transactions and failure modes

@Transactional(readOnly = true) on the service method, not the controller, so the transaction boundary matches the single query. Read-only marks the transaction and the JDBC connection as read-only, which prevents accidental writes through that path and signals the intent to the pool and to Oracle. I would not use @Transactional on a controller method that only delegates, and I would not mark the repository method read-only and the service method writable. One boundary, at the service.

Isolation stays at the Oracle default, READ COMMITTED. For a sum over CDR rows that is the right default. SERIALIZABLE would give a repeatable total across the window but would raise ORA-08177 under concurrent CDR ingestion, and billing reads do not need that guarantee. If a caller needs a total that matches a bill run, that is a different endpoint backed by a snapshot or a rated-usage table, not a live CDR sum.

Two failure modes I would name in the interview. First, pool exhaustion. HikariCP with, say, 20 connections and a 5 second query timeout means 20 slow aggregations block every other endpoint in the microservice. The fix is a separate datasource and pool for reporting-style reads, or a circuit breaker that returns 503 with code: upstream_unavailable instead of queueing. Second, a subscriber with no calls. SUM over zero rows returns NULL in Oracle, so the coalesce in the query and the orElse(0L) in the service both guard the same case. Returning 0 with the requested window is correct here. Returning 404 would be wrong, because the subscriber resource is not the target of this request. The target is a computed collection over a window, and an empty collection has a valid representation.

What I would add before calling it done

A Cache-Control: max-age=60 header, because call duration totals change only when new CDRs land, and a 60 second cache absorbs repeated polling from a care app without serving stale billing data for long. An EXPLAIN PLAN check in CI against a representative CDR volume, so a missing index shows up as a test failure rather than a production slowdown. And a test with a call that starts at 23:59 on the to date, which is the case the half-open window exists to handle.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8You are given a directed graph representing provisioning steps for activating a new mobile line, with edges representing dependencies. Detect whether there is a cycle in this dependency graph. If a cycle exists, return true; otherwise, false. Discuss your approach and complexity?

Reported in Software Engineer II – Backend (Telecom BSS/OSS) interview at America Movil

The 90-second answer

I would run a depth-first search with three states per node: unvisited, in the current recursion stack, and finished. If I reach a node that is in the current stack, I have found a back edge, so there is a cycle. If I finish a node, I mark it finished and remove it from the stack. I start the search from every unvisited node, because a provisioning graph for a mobile line is rarely connected: SIM activation, number porting, and billing setup may sit in separate components.

That gives O(V + E) time and O(V) extra space for the state array and the explicit stack. In Java I would write it iteratively. A recursive version is shorter, but a provisioning graph built from a catalogue of steps can be deep enough to overflow the JVM stack, and an explicit stack makes that failure mode disappear.

Java
// Java 17. Returns true if the directed dependency graph has a cycle.
public boolean hasCycle(Map<String, List<String>> graph) {
    // 0 = unvisited, 1 = on current path, 2 = finished
    Map<String, Integer> state = new HashMap<>();
    for (String node : graph.keySet()) state.put(node, 0);

    for (String start : graph.keySet()) {
        if (state.get(start) != 0) continue;
        // Each frame: node, next neighbour index to try
        Deque<String> stack = new ArrayDeque<>();
        Deque<Integer> nextIdx = new ArrayDeque<>();
        stack.push(start);
        nextIdx.push(0);
        state.put(start, 1);

        while (!stack.isEmpty()) {
            String node = stack.peek();
            List<String> neighbours = graph.getOrDefault(node, List.of());
            int i = nextIdx.pop();
            if (i < neighbours.size()) {
                nextIdx.push(i + 1);
                String nxt = neighbours.get(i);
                int s = state.getOrDefault(nxt, 0);
                if (s == 1) return true;          // back edge to an ancestor
                if (s == 0) {
                    state.put(nxt, 1);
                    stack.push(nxt);
                    nextIdx.push(0);
                }
            } else {
                state.put(node, 2);
                stack.pop();
            }
        }
    }
    return false;
}

Worked trace

Take a small activation graph: reserve_number -> create_subscriber -> activate_sim, plus activate_sim -> reserve_number as a bad dependency, and an isolated send_welcome_sms.

StepActionState changeResult
1Start DFS at reserve_numberreserve_number = 1stack: reserve_number
2Follow edge to create_subscribercreate_subscriber = 1stack: reserve_number, create_subscriber
3Follow edge to activate_simactivate_sim = 1stack grows by one
4Edge activate_sim -> reserve_number, state 1noneback edge found, return true

If that last edge were absent, step 4 would finish activate_sim (state 2), unwind through create_subscriber and reserve_number, then the outer loop would start at send_welcome_sms, finish it, and return false. The outer loop over all nodes is what catches a cycle hiding in a disconnected component.

Why not just count a topological sort

Kahn's algorithm is the credible alternative: repeatedly remove nodes with indegree zero, and if fewer than V nodes come out, a cycle remains. It is O(V + E) too, and in this domain it has a bonus, because the removal order is a valid provisioning sequence when the graph is acyclic. I would pick Kahn if the caller needs that order, which a BSS provisioning orchestrator usually does. I would pick the three-colour DFS if the caller only needs the boolean, or if I want to report the actual cycle. DFS can recover the cycle by recording parent pointers and walking back from the node that closes the loop, which is far more useful in an incident: "activate_sim depends on reserve_number depends on activate_sim" tells the catalogue team exactly which dependency to fix.

Edge cases that break naive versions

A self-loop, a step that depends on itself, is a cycle of length one. The code above handles it: the node is state 1 when its own neighbour is examined, so it returns true. A neighbour that appears only as a target and never as a key is treated as a node with no outgoing edges via getOrDefault, so it gets finished rather than throwing. Duplicate edges do not change the answer, only the constant factor. The one case to state up front: this detects a cycle, it does not prove the graph is a good provisioning plan. A DAG can still order steps in a way that fails at runtime, for example activate_sim before the subscriber record exists, if nobody encoded that dependency as an edge.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-9Describe a time you disagreed with a teammate or architect about a design decision (for example, monolith vs microservices). How did you handle it, and what was the final outcome?

Reported in Software Engineer II – Backend (Telecom BSS/OSS) interview at America Movil

The 90-second answer

On a BSS order and charging project I disagreed with the architect about splitting a new billing service into six microservices on day one. I did not argue for a monolith in principle. I argued that we had no proven service boundaries yet, a team of four backend engineers, and a hard requirement for atomic order plus rating plus invoice creation. Splitting first would have turned every order into a distributed transaction we had to build before we knew the domain.

I proposed a modular monolith with strict internal boundaries, and a spike to test the one boundary we were most confident about. The architect agreed to the spike, the numbers settled it, and we shipped the modular version in one deployable. Six months later we extracted the rating service, which was the only one with independent scaling and release pressure.

What I actually did

The context: a prepaid top-up and bundle activation flow for a Latin American operator. The proposed design had separate services for customer, order, rating, payment, notification, and audit, each with its own database and Kafka topics. My concern was specific. Activation had to be all or nothing. If the order committed and rating failed, the subscriber paid for a bundle they could not use, and support had to reconcile it manually.

I wrote the disagreement down in a one page ADR instead of debating it in the meeting. It stated the assumption I was challenging: that the six domains were already stable. They were not. Product was still changing bundle rules weekly, and two of the proposed services shared the same aggregate, the subscriber balance.

Then I ran a small comparison with the team, using our own load profile as the input. The figures below are from that spike, labelled as measured on our staging environment at the time.

OptionOrder activation pathp99 latency in spikeFailure mode we saw
Six microservices, saga per orderAPI to order, Kafka to rating, Kafka to payment, callback to order640 ms3.1% of orders stuck in pending after a rating timeout, needed manual replay
Modular monolith, one transactionSingle service, modules call each other in process180 msNo partial activation, rollback on any module failure
Modular monolith, rating extracted laterIn process now, rating behind an interface210 msRating timeout returned as a clean 503, order not committed

The spike changed the conversation from taste to evidence. The architect kept the microservices target for rating, because rating had 10x the CPU cost and a separate release cadence from the billing team. We agreed to extract it only after the interface had been stable for two releases.

How the modular version was structured

The point was not one big class. Each module owned its tables and exposed a narrow interface, so extraction later was mechanical.

Java
// Java 17, checked against the project codebase at the time
public interface RatingPort {
    RatingResult rate(RatingRequest request);
}

// Inside the monolith: direct call, same transaction boundary
public final class LocalRatingAdapter implements RatingPort {
    private final RatingModule rating;
    public RatingResult rate(RatingRequest request) {
        return rating.rate(request); // throws RatingUnavailableException
    }
}

// Later, after extraction: same interface, HTTP client behind it
public final class HttpRatingAdapter implements RatingPort {
    private final RatingClient client;
    public RatingResult rate(RatingRequest request) {
        return client.rate(request); // same exception contract
    }
}

Order orchestration called RatingPort and never imported rating internals. That is what let us swap the adapter without touching order code.

later Order API Order module RatingPort Local rating now Rating service Order DB

Outcome and what I would do differently

We shipped in 11 weeks instead of the 20 estimated for the split, with zero partial activations in the first month. The rating extraction took three weeks later because the port and the contract tests already existed. The architect and I kept working together on the next design, which I think happened because I challenged the sequencing, not his competence, and I brought a reversible alternative.

If I ran it again I would involve the SRE earlier. The spike measured latency well but underweighted operational cost. Six services meant six dashboards, six on call rotations, and tracing across Kafka topics that the team had not run in production before. I should have put that cost in the ADR table from the start, not just the latency column.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-10Describe a challenging project you worked on and how you resolved technical issues?

Reported in Software Engineer interview at America Movil

The 90-second answer

I led the backend for a prepaid usage-rating service that had to rate call detail records (CDRs) and update balances in near real time for about 8 million subscribers in Mexico. The hard part was not the rating rules. It was that the same CDR could arrive twice, arrive late, or arrive out of order, and a duplicate rating would charge a customer twice.

We rebuilt ingestion around three decisions: deduplicate on a natural key before rating, partition by subscriber so one subscriber's records stay ordered, and make every balance update idempotent and auditable. That took p99 rating latency from roughly 900 ms to 210 ms in our load test, and duplicate charges in the reconciliation report dropped to zero over the first month after cutover.

What broke first

The original pipeline consumed CDR files from two network vendors into Kafka, rated them in a stateless service, and wrote to a single MySQL table keyed by an auto-increment id. Under a holiday peak we saw 14 million CDRs in a day, about 160 per second average and 1,100 per second at peak. Three failures showed up together.

First, vendors resent files after a timeout, so we got exact duplicates with different file ids. Second, a small set of high-volume subscribers landed on one Kafka partition and one database shard, so that shard saturated while others sat idle. Third, late CDRs for calls that started before midnight were rated against the next day's tariff, which finance flagged in reconciliation.

How we fixed it

We defined the deduplication key from the source, not from our pipeline: vendor_id + switch_id + call_reference + start_time. The consumer checks that key in a rated_cdrs table inside the same transaction as the balance update. If the key exists, it replays the stored result instead of rating again.

Java
// Java 17, checked against Spring Kafka 3.x consumer semantics
@Transactional
public RatingResult rate(Cdr cdr) {
    var key = DedupKey.of(cdr.vendorId(), cdr.switchId(),
                          cdr.callReference(), cdr.startTime());
    return ratedRepo.findByDedupKey(key)
        .map(existing -> existing.result())
        .orElseGet(() -> {
            RatingResult r = ratingEngine.rate(cdr);
            balanceRepo.apply(r.subscriberId(), r.deltaCents(), r.idempotencyKey());
            ratedRepo.save(new RatedCdr(key, r));
            return r;
        });
}

Partitioning changed to hash on subscriber_id with 64 partitions, so a single subscriber stays ordered and load spreads across shards. We also added a watermark: CDRs with start_time more than 6 hours behind the stream watermark go to a late-record topic, get rated with the tariff for their actual start day, and emit an adjustment entry instead of silently changing today's balance.

new duplicate CDR file from vendor Validate and normalise Kafka by subscriber hash Dedup check on natural key Rate and apply balance Replay stored result Write audit record

Worked trace

TimeEventBefore fixAfter fix
23:58Call starts, rated at 0.04 MXN per minuteRated on 1 Jan tariffRated on 1 Jan tariff
00:12Same CDR resent by vendor with new file idSecond charge, new row idDedup key hit, no second charge
02:00Late CDR from 20:00 arrivesApplied to 2 Jan balanceLate topic, adjustment dated 1 Jan
Peak1,100 CDRs per secondOne shard at 100% CPU64 partitions, max shard at 61% CPU

Trade-offs I would name in the loop

The dedup table grows fast, about 14 million rows a day in that example, so we partitioned it by day and archived to object storage after 30 days. That keeps the hot lookup under 5 ms. The cost is storage and a nightly archive job that needs its own alert if it lags.

Ordering by subscriber helps consistency for one customer, but it means a hot subscriber can still skew a partition. We accepted that because per-subscriber ordering mattered more for balance correctness than perfect load balance, and we capped the impact by keeping rating stateless so partitions could be rebalanced.

If I started again I would add a shadow mode first: run the new dedup and partitioning in parallel for a week, compare balances per subscriber against the old pipeline, and only cut over when the daily reconciliation diff was below 0.01%. That comparison is what convinced operations to accept the migration window.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11How do you stay updated with new technologies?

Reported in Software Engineer interview at America Movil

The 90-second answer

I run a fixed weekly loop, not random reading. I pick two primary sources in the stack I work on, read their changelogs and release notes, and try one thing hands-on that week. At América Móvil scale, that discipline matters because a new framework version is not just an API change. It can mean a new JVM behaviour under 20,000 prepaid charging requests per second, a different Kafka client retention policy for CDR streams, or a database driver that changes connection pooling. I do not adopt anything in production from a blog summary.

My sources are boring on purpose: the official documentation and changelog for Java, Spring, Kafka, PostgreSQL or Oracle as relevant, the RFC when a protocol changes, and the vendor security advisories. I spend about 90 minutes on Friday. I log what changed, what breaks backward compatibility, and what I tested. If I cannot reproduce it locally, I do not claim I know it.

How I decide whether to use it

A technology only moves from learning to a proposal when it passes a short evaluation. I score it against the constraints of the system I own.

CriterionQuestion I askExample from telecom work
CompatibilityDoes it run on our current JDK, OS and database versions?A new JDBC driver that drops support for the Oracle version in our data centres is out, however good the benchmarks look
OperabilityCan we observe, roll back and scale it?A streaming library with no backpressure metrics makes CDR aggregation harder to run at 2 a.m.
Cost at scaleWhat does it cost per million events or per subscriber?Parsing cost per CDR, memory per connection, licence cost per core
Exit pathCan we remove it in one release?A library that leaks its types into our public API creates lock-in

I write that evaluation down in a one-page note with a small benchmark. Hypothetical example: if I test a JSON parser for CDR ingestion, I measure throughput on 1 million records, p99 latency, and heap after a 10 minute run, then compare it with the current parser on the same machine. A 15% speed gain that doubles heap is usually a no.

Java
// Evaluation harness I keep for a candidate library, Java 17
// Run the same workload against old and new implementations.
var records = Files.lines(Path.of("cdr-sample.ndjson")).limit(1_000_000).toList();
long start = System.nanoTime();
long totalSeconds = records.stream().mapToLong(parser::durationSeconds).sum();
long elapsedMs = (System.nanoTime() - start) / 1_000_000;
System.out.printf("records=%d totalSeconds=%d elapsedMs=%d%n", records.size(), totalSeconds, elapsedMs);

The point is not the snippet. It is that the claim "faster" becomes a number I can repeat in a design review.

What the loop looks like in practice

No Yes No Yes Read changelog and docs Reproduce in a small spike Passes compatibility, cost and operability checks? Log decision and revisit date Propose behind a feature flag Roll out to one country or one service Metrics hold for two weeks? Roll back Adopt and update runbook

That rollout step is where a lot of learning fails. I have seen a team adopt a new HTTP client because it was fashionable, then discover it buffered responses differently and broke a timeout assumption in a charging flow. My spike now includes the failure case: timeout, retry, and a downstream dependency returning 503. If the new library changes retry behaviour, I want to see it in the spike, not in production.

Keeping up without falling behind on the basics

I also keep a quarterly review of the fundamentals that do not change as fast: concurrency, transactions, partitioning, and network failure modes. New tools sit on top of those. A new stream processor does not remove the need to understand exactly-once semantics, ordering per subscriber key, and what happens when a broker loses a partition. When I read about a new release, I map it back to those questions first.

I share what I find in a short note to the team, with the primary source linked and the test results attached. That keeps the knowledge in the team instead of in my browser history, and it gives reviewers something concrete to challenge. If the note is wrong, the benchmark usually shows it quickly.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-12Can you walk us through your approach to debugging a performance issue in a production system?

Reported in Software Engineer interview at America Movil

The 90-second answer

I start by pinning down the symptom in numbers, not adjectives. Which service, which endpoint or pipeline stage, what changed, and what the baseline was before. For a prepaid charging service I would want p50 and p99 latency, throughput, error rate, and saturation for CPU, memory, threads, and database connections, split by country or data centre if traffic is regional. Then I check whether the problem is latency, throughput, or both, and whether it tracks traffic, a deploy, a data change, or a dependency.

Only after that do I form a hypothesis and test it with a measurement I can repeat. I do not restart things or tune parameters on a hunch in production. If I cannot reproduce it in staging with production-like data volume, I use production traces and profiles to narrow it down.

A concrete case I would describe: p99 on POST /charging/authorize went from 45 ms to 900 ms over 20 minutes during a peak in Mexico, while p50 stayed near 40 ms. That pattern points away from a general code slowdown and toward queuing or a tail dependency. Throughput held, so the service was not CPU saturated overall.

How I narrow it

First, I segment the trace. I pull a sample of slow requests from distributed tracing and compare their spans with fast requests from the same window. If the extra 850 ms sits in one span, that span is the suspect. If it sits in queue time before the handler runs, I look at the load balancer, thread pool, and connection pool.

Second, I check the usual saturation signals in the same window: JVM GC pause time and heap, thread pool queue depth, database active sessions and lock waits, Kafka consumer lag if the path is event driven, and downstream latency for the balance store or HLR/HSS lookup. I also check for a noisy neighbour, a retry storm, or a slow query plan after a statistics update.

Third, I profile rather than guess. For Java, async-profiler or a short heap and thread dump during the incident often shows whether time goes to lock contention, GC, or a specific call. For the database, I look at pg_stat_statements or the equivalent slow query log and check for a plan change, missing index use, or lock waits on a hot row such as a subscriber balance.

Signal at 14:00 to 14:20ObservationWhat it rules in or out
p50 40 ms, p99 900 msTail onlyNot a uniform code regression
CPU 55 percent, heap stableNo saturationNot GC or CPU bound
DB pool wait 700 ms on 30 percent of requestsPool exhaustedQueuing before queries run
One query at 2 ms averageDB itself fastNot a slow query
Active DB sessions capped at 20Pool limit hitSomething holds connections open

In that trace the pool wait explained the tail. The next question was why connections were held. A downstream call inside the database transaction, for example a synchronous rating call made while holding a connection, would do it. Under load, 20 connections each held for 200 ms caps throughput at about 100 requests per second for that path and queues the rest.

Confirming and fixing

I confirm with a targeted check before changing code. I add or read a metric for connection hold time and for time spent waiting for a connection, then correlate it with the downstream span. A small snippet I use for that kind of timing in Java is:

Java
Timer.Sample sample = Timer.start(registry);
try (Connection c = pool.getConnection()) {
    long holdStart = System.nanoTime();
    try {
        return chargingService.authorize(request, c);
    } finally {
        registry.timer("db.connection.hold").record(System.nanoTime() - holdStart, TimeUnit.NANOSECONDS);
    }
} finally {
    sample.stop(registry.timer("charging.authorize"));
}

If hold time spikes only when the downstream rating span is slow, the fix is structural: move the external call outside the transaction, set a tight timeout and circuit breaker on that call, and size the pool from measured hold time rather than a default. Little's law gives a quick check. At 500 requests per second with a 50 ms hold, I need about 25 connections in steady state, plus headroom for spikes. A pool of 20 was undersized once hold time tripled.

I roll the fix behind a flag or a canary in one region first, watch p99 and pool wait for at least one peak window, and compare against the pre-incident baseline. Then I add an alert on pool wait time and on the downstream timeout rate, because those would have paged me 15 minutes earlier.

What I avoid

I avoid raising the pool size as the first move. That can push the queue into the database and turn a contained slowdown into a database outage. I also avoid tuning JVM flags from a single GC graph without checking allocation rate and pause percentiles. And I avoid closing the incident when p99 recovers. Recovery can mean traffic dropped. I want the same traffic level with the fix in place, plus a load test that reproduces the original hold time pattern.

Define symptom and baseline Segment slow traces Check saturation signals Profile CPU, GC, DB, pool Confirm with one metric Fix behind canary Verify at peak and alert

That sequence keeps the work evidence driven. The interviewer usually follows up on one branch, so I am ready to go deeper on tracing, on database locks, or on how I would reproduce a CDR pipeline lag with replayed records in staging.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13Why do you want to work at America Movil?

Reported in Software Engineer interview at America Movil

The 90-second answer

Assuming this is a backend or platform role, not a product management one, I applied because I want to work on systems where a mistake shows up immediately for real customers. In prepaid telecom that means a balance enquiry, a top-up, or a usage alert. If the service is slow or inconsistent, the customer notices in seconds and operations gets a call. I have worked on high-throughput Java services with idempotent consumers and reconciliation jobs, and I want the harder version of that work, with retries from the network edge, out-of-order records, and audit requirements I have to design for from the start.

I looked at the public footprint before applying. Telcel in Mexico and Claro in several Latin American markets are prepaid first, so the engineering problem is consistency and latency at scale, not adding another feature to a dashboard. The multi-country setup also means local rules for tax, identity checks and data residency, which I find more interesting than building the same service for one market.

My decision process was fairly concrete. I compared three kinds of offer I had seen. A small startup would give me faster greenfield work and more ownership of product choices. A large consumer tech company would give me scale, but mostly inside one regulatory regime. This role sits in between. The scale is large, the change process is slower because of regulation and change control, and I would have to work across Spanish and Portuguese speaking teams and with operations on call. I am willing to accept the slower release cycle for that operational reality. If I wanted to ship a new feature every week with no compliance review, I would not apply here, and I would be honest about that mismatch.

In the first months I would trace one request end to end, say a prepaid balance check, through the gateway, charging service, database and audit log. I would learn the failure modes that already have runbooks, such as duplicate files, late records and a downstream service timing out, and I would make my first change small and measurable. For example, tightening a retry path or adding a reconciliation check between streamed usage and the billing record, with p99 latency or processing lag measured before and after.

I do not know the local regulation for the country I would join, and I would not pretend otherwise in this interview. I have worked under retention and audit constraints before, and I read the local rules and design for traceability. That is a gap I can close quickly. What I bring is experience with the failure patterns that cause those audits to fail.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-14Implement a function to find the longest substring without repeating characters?

Reported in Software Engineer interview at America Movil

The 90-second answer

I would use a sliding window with the last index of each character. Keep left at the start of the current window and move right across the string once. When s[right] was last seen inside the window, move left to one past that previous occurrence. The window [left, right] never contains a repeat, and its length is the best length ending at right. Track the maximum and its start as you go. That is O(n) time and O(min(n, alphabet)) extra space.

Java
// Java 17
public static String longestUniqueSubstring(String s) {
    if (s == null || s.isEmpty()) return "";

    Map<Character, Integer> lastSeen = new HashMap<>();
    int left = 0, bestStart = 0, bestLen = 0;

    for (int right = 0; right < s.length(); right++) {
        char c = s.charAt(right);
        Integer prev = lastSeen.get(c);
        if (prev != null && prev >= left) {
            left = prev + 1;
        }
        lastSeen.put(c, right);
        int len = right - left + 1;
        if (len > bestLen) {
            bestLen = len;
            bestStart = left;
        }
    }
    return s.substring(bestStart, bestStart + bestLen);
}

Worked trace

For s = "abca":

rightcharprevleft after stepwindowbest
0anone0aa (1)
1bnone0abab (2)
2cnone0abcabc (3)
3a01bcaabc (3)

At right = 3 the previous a sits at index 0, which is inside the window, so left jumps to 1. The new window bca has length 3, which does not beat the stored best, so the answer stays abc.

Why this beats the alternatives

ApproachTimeSpaceWhen it is acceptable
Brute force, check every substringO(n^3) with a set per substring, O(n^2) if you expand and stop at first repeatO(n)Only for tiny inputs in a take-home
Sliding window with a HashSet of the windowO(n) average, but each shrink step removes from the setO(window)Fine, and simpler to explain, but the last-index map avoids the inner shrink loop
Sliding window with last-index map (above)O(n)O(alphabet)Default choice

The invariant is what makes it correct. After processing right, [left, right] is the longest repeat-free substring ending at right. Any shorter window ending at right cannot beat it, and any window ending earlier was already considered. So scanning once and keeping the maximum is enough. No need to restart the window from scratch after a repeat.

Edge cases I would raise before coding

Empty and null input: return "" for empty, and decide on null explicitly (return "" or throw IllegalArgumentException) rather than letting a NullPointerException surface mid-loop. In a telecom service parsing CDR fields, I would throw on null at the boundary and keep the core function total on non-null input.

Unicode: charAt returns a UTF-16 code unit, so an emoji stored as a surrogate pair counts as two units and could be split across the window boundary. If the input is user text rather than ASCII identifiers, iterate with codePointAt and store code points, or state the assumption that the input is ASCII or BMP text. For subscriber IDs and call references at América Móvil that assumption usually holds, but I would not silently ship the char version for free-text fields.

Alphabet size: a HashMap is fine for general text. If the input is known to be lowercase ASCII, an int[128] array of last positions is faster and avoids boxing. For a 10 million character log line, the map version still runs in a single pass, roughly tens of milliseconds, while the O(n^2) expansion would need on the order of 10^14 operations and never finish.

If the interviewer asks for length only, drop the substring call and return bestLen. If they ask for all longest substrings, collect every window whose length equals bestLen instead of keeping a single start index.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-15Design a system to handle millions of IoT device updates per minute?

Reported in Software Engineer interview at America Movil

The 90-second answer

I would clarify scale first. Say 2 million updates per minute sustained, which is 33,000 per second, with a 3x peak at 100,000 per second. Each update is small, say 200 to 300 bytes: device id, timestamp, metric name, value, firmware version. Devices are on intermittent 2G, 4G or NB-IoT links, so the design has to tolerate duplicates, out of order arrival and long offline periods. The write path is append only. No device ever waits on a database transaction to acknowledge a reading.

Device MQTT gateway per country Kafka, partitioned by device_id Stream processor Time series store Alert and rule engine Lakehouse for history Device shadow store

The gateway terminates MQTT or CoAP over TLS, authenticates with a per device certificate, and publishes to Kafka. It does not parse business rules. Kafka absorbs the burst when a region reconnects after an outage. The stream processor maintains the latest value per device, computes rolling aggregates, and emits alerts. The time series store serves current state queries. Raw events land in the lakehouse for billing, audit and model training.

Sizing, with real figures

At 100,000 messages per second peak and 250 bytes per message, ingress is 25 MB per second, about 200 Mbps before protocol overhead. Kafka with replication factor 3 and 24 hours retention holds roughly 100,000 x 86,400 x 250 bytes = 2.16 TB of raw payload, about 6.5 TB with replication. Partition count follows consumer throughput, not topic count. If one consumer instance sustains 20,000 messages per second with batching, 100,000 per second needs at least 5 active consumers, so I would start with 48 partitions and leave headroom for rebalancing. Partitioning by hash of device id keeps all updates for one device in order on one partition, which is what makes last value and deduplication cheap.

ComponentChoiceLimit it hits
---------
IngestMQTT gateway, stateless, autoscaledTLS handshake rate per gateway node
BufferKafka, 48 partitions, RF 3, min.insync.replicas 2Disk and replication bandwidth at peak
ProcessingFlink or Kafka Streams, checkpointedState size for per device windows
ServingCassandra or ScyllaDB keyed by device id, or a time series storeHot devices that update every second
HistoryObject storage in Parquet, partitioned by day and countryLate data arriving days later

Deduplication and ordering

Devices retry, gateways retry, and Kafka delivers at least once. Every message carries a device generated sequence number and event timestamp. The processor keeps the highest sequence seen per device in its state store and drops anything at or below it. That handles duplicates without a global lock. Event time, not processing time, drives windows, with an allowed lateness of, say, 10 minutes for late readings. Anything later goes to a side output and still lands in the lakehouse, but it does not rewrite a closed alert window. Clock skew on cheap devices is common, so I would flag readings more than 24 hours from gateway receipt time for quarantine instead of trusting them blindly.

A consumer sketch in Java, checked against Kafka clients 3.7:

Java
// key: deviceId, value: Update(deviceId, seq, eventTs, metric, value)
props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, "false");
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "500");

while (true) {
    var records = consumer.poll(Duration.ofMillis(200));
    for (var r : records) {
        Update u = parse(r.value());
        long lastSeq = state.getOrDefault(u.deviceId(), -1L);
        if (u.seq() <= lastSeq) continue; // duplicate or replay
        state.put(u.deviceId(), u.seq());
        sink.writeLatest(u);            // idempotent upsert by deviceId
        alerts.evaluate(u);            // emits only on threshold crossing
    }
    consumer.commitSync(); // after sink write, not before
}

Committing after the sink write means a crash replays the batch and the sequence check drops the duplicates. Committing before it would lose readings silently.

Failure modes I would name in the interview

A hot partition appears when one fleet gateway or one device model dominates traffic, or when hashing is poor. I would monitor per partition lag and per partition message rate, and keep the ability to split a hot device id out to its own topic. A poison message, one that fails parsing every time, blocks a partition. It goes to a dead letter topic after a fixed number of attempts, with the raw payload preserved. Backpressure: if the time series store slows, the processor must slow its poll rate and let Kafka lag grow rather than drop readings, and lag becomes the alert metric. For América Móvil scale, I would also keep processing and storage in country, since device telemetry and subscriber linked data often cannot leave the jurisdiction, and run gateways in at least two availability zones per country so a zone loss does not cut off a whole fleet.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16Tell me about a time you had to refactor a legacy system?

Reported in Software Engineer interview at America Movil

The 90-second answer

I refactored a legacy CDR rating job at a telecom operator. It was a 9-year-old Java batch process, about 14,000 lines, that read call detail records from flat files, called Oracle stored procedures per record, and wrote rated records for billing. It worked, but nobody could change rating rules safely. A single rule change in 2022 took three weeks and broke weekend billing.

I did not propose a rewrite. I proposed a strangler refactor in four slices, each one shippable and reversible, with the old path still producing the billing file until the new path matched it byte for byte on a full day of traffic.

What I found first

I spent the first two weeks measuring, not editing. I added counters around the stored procedure calls and timed each stage for one representative day: 18 million CDRs, hypothetical figures from that run, 6.1 hours wall clock, 41% of it inside three stored procedures, and 2,300 per-record exceptions that were logged and dropped. That last number mattered. The business thought rating covered every record. It did not.

I also wrote characterization tests before touching logic. I captured 50,000 input records with their expected outputs from production, including the ugly cases: calls crossing midnight, calls with zero duration, and records with a missing cell ID. Those tests became the contract. If a refactor changed an output for those inputs, the build failed.

The refactor itself

Slice one extracted the rating rules out of the stored procedures into a pure Java function with no database access. Slice two replaced per-record procedure calls with batched reads. Slice three split the monolith into three stages with files as the boundary: parse, rate, write. Slice four deleted the stored procedures only after two weeks of parallel runs.

Java
// Before: rule logic buried in a stored procedure, called per record
// After: pure function, testable without Oracle
public Rating rate(Cdr cdr, RatingRules rules) {
    long billableSeconds = Math.max(0, cdr.endEpoch() - cdr.startEpoch());
    if (cdr.callType() == CallType.VOICE && billableSeconds > 0) {
        billableSeconds = ((billableSeconds + 59) / 60) * 60; // round up to minute
    }
    long charge = billableSeconds * rules.ratePerSecond(cdr.destinationPrefix());
    return new Rating(cdr.id(), billableSeconds, charge);
}

The rounding rule above looks trivial. In the old code it lived in a stored procedure with an off-by-one for calls under 60 seconds, and finance had built a manual adjustment around that bug. Extracting it forced a decision: keep the bug for parity, or fix it with finance sign-off. We kept parity in slice one, then fixed it in slice four with a documented adjustment file. That sequencing is what got approval.

comparison run diff check CDR files Parse stage Rate stage - pure Java Write stage Billing file Old stored procedures Byte-for-byte match

How I proved it was safe

PhaseGuardrailExit criterion
---------
---------
---------
Parallel runBoth paths write to separate directories14 consecutive days, zero diffs on rated amount
Shadow billingFinance reconciles totals dailyVariance under 0.01% for 10 business days
CutoverFeature flag per rating rule groupRollback tested by replaying one day in under 40 minutes

Runtime fell from 6.1 hours to 1.4 hours because batched reads removed per-record round trips. The 2,300 dropped records per day became a dead-letter file with a reason code, and operations started alerting on it. That surfaced a real upstream bug: one switch was sending end times before start times after a clock change.

What I would not do again

I initially wanted to move straight to a streaming design with Kafka. The team pushed back, correctly. Batch billing had a hard deadline of 06:00 and a file contract with finance. Streaming would have changed the contract and the failure mode without fixing the rating logic. I kept batch, fixed the logic, and left streaming as a later option once the rules were testable.

The outcome I quote in interviews: no billing incident during cutover, rule changes went from three weeks to two days because the rules were now unit tested, and the dead-letter alert caught the clock bug within a week. The lesson I took from it is that refactoring legacy code is mostly about building a safety net first. The code change is the easy part.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17You are given a stream of mobile data usage records with subscriberId, timestamp, and bytesUsed. Design and implement a function in Java that, for a given subscriber and current timestamp, returns the total bytes used in the last 30 days, optimized for high throughput?

Reported in Senior Software Engineer, BSS/OSS Platforms interview at America Movil

The 90-second answer

I keep a per-subscriber sliding window in memory with a running total. Adding a record inserts it into that subscriber's window and adds to the total. Querying evicts every entry at or before now - 30 days, subtracts those bytes, and returns the total. The lock is per subscriber, so unrelated subscribers do not block each other.

Assumptions I state up front: timestamps are epoch millis from the mediation feed, bytesUsed is non-negative, and the query timestamp is passed in as now rather than read from the system clock inside the method. That makes the function testable and replayable. I also confirm the boundary with the billing owner: a record exactly 30 days old is excluded here.

Java
// Java 17. One window per active subscriber.
public final class UsageWindow {
    private static final long WINDOW_MS = 30L * 24 * 60 * 60 * 1000;

    // tsMs -> bytes at that timestamp. TreeMap keeps out-of-order
    // records sorted, so eviction always removes the oldest first.
    private final TreeMap<Long, Long> events = new TreeMap<>();
    private long totalBytes;

    public synchronized void add(long tsMs, long bytes) {
        if (bytes < 0) throw new IllegalArgumentException("bytes < 0");
        events.merge(tsMs, bytes, Long::sum);
        totalBytes += bytes;
    }

    public synchronized long totalLast30Days(long nowMs) {
        long cutoff = nowMs - WINDOW_MS;
        while (!events.isEmpty() && events.firstKey() <= cutoff) {
            totalBytes -= events.pollFirstEntry().getValue();
        }
        return totalBytes;
    }
}

public final class UsageTracker {
    private final ConcurrentHashMap<String, UsageWindow> windows = new ConcurrentHashMap<>();

    public void add(String subscriberId, long tsMs, long bytes) {
        windows.computeIfAbsent(subscriberId, k -> new UsageWindow()).add(tsMs, bytes);
    }

    public long totalLast30Days(String subscriberId, long nowMs) {
        UsageWindow w = windows.get(subscriberId);
        return w == null ? 0L : w.totalLast30Days(nowMs);
    }
}

synchronized on the window serializes add and query for the same subscriber. computeIfAbsent on the map is the only shared contention and it is brief. Add is O(log n) in the number of distinct timestamps in the window, and eviction is amortized O(log n) per evicted entry because each entry is inserted and removed once. If records are known to arrive in order, an ArrayDeque gives O(1) amortized add, but it is only correct under that guarantee. I would not use it when late records are expected.

Worked trace

ts (days ago)bytesActiontotalBytes after
401,000,000,000add1,000,000,000
29500,000,000add1,500,000,000
10200,000,000add, out of order relative to a later record below1,700,000,000
1100,000,000add1,800,000,000
0 (query now)-evict ts <= now - 30d, removes the 40-day entry800,000,000

The query returns 800,000,000. Because the map is sorted, a late record for day 20 inserted after the day 1 record still lands in the correct position and is evicted at the correct time.

Alternatives and when I would switch

ApproachAdd / query costMemory per subscriberPrecisionUse when
TreeMap window (above)O(log n) add, amortized evictionO(distinct timestamps in 30 days)Exact per recordLate records expected, exactness required
ArrayDeque windowO(1) amortizedO(events in 30 days)Exact, in-order onlyFeed guarantees ordering
Hourly ring buffer, 720 slotsO(1)720 longs, about 5.7 KB plus overheadOff by up to 1 hour at the edgeHigh event rate, hourly tolerance acceptable
DB index (subscriber_id, ts) plus SUMO(log n) query plus round tripNone in appExactQuery rate is low, or durability and audit matter more than latency

Memory decides this at scale. Hypothetical sizing, labelled as such: if a deployment had 5 million active subscribers averaging 200 data sessions a month, that is 1 billion events in 30 days, which no single in-memory structure holds. In production I would shard by subscriberId hash across nodes, expire windows after 30 days of inactivity, and persist events to a durable store or topic so a node restart can rebuild by replaying the last 30 days. Hourly buckets cut memory by roughly the events-per-hour factor and make late records cheap to merge, at the cost of edge precision. I would use hourly buckets for the real-time counter and keep the exact event store as the system of record for billing disputes.

Failure modes I would name

Late and out-of-order records from network elements arrive hours later. The TreeMap handles ordering, but a record older than the cutoff is inserted and then immediately evicted on the next query, which is correct for the total yet wasteful. Detection: track a late-record counter and a max-lateness watermark. If lateness grows, merge late records into hourly buckets instead of the exact map.

Clock skew produces future timestamps. A record dated tomorrow inflates the total and blocks eviction for a day. I would quarantine records more than 5 minutes ahead of the tracker's clock and alert on the rate.

Overflow is quiet: summed over 30 days, a heavy user's bytes exceed 32-bit range easily, so every field is long, and I would test a 100 GB month explicitly.

Finally, one JVM is a single point of loss. The code above is the per-node component. The surrounding system partitions subscribers across nodes, replicates the stream, and rebuilds windows on failover by replaying the last 30 days, which is why the persisted event store matters even though the hot path never touches it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18Design a prepaid balance management service for América Móvil that supports high-volume top-ups and deductions across multiple countries, guaranteeing a subscriber's balance never goes negative due to concurrent requests and providing an audit trail?

Reported in Senior Software Engineer, BSS/OSS Platforms interview at America Movil

The 90-second answer

I would keep one authoritative balance row per subscriber, in the subscriber's home-country shard, and make every deduction a single conditional update that only succeeds when funds are sufficient. Top-ups and deductions both write an append-only ledger entry in the same database transaction as the balance change, keyed by a client-supplied idempotency key. That gives three properties in one mechanism: no negative balance under concurrency, safe retries after timeouts, and a replayable audit trail.

Assumptions I would state up front: amounts are integer minor units (cents, centavos) in the account currency, a subscriber's balance lives in exactly one country shard at a time, and cross-country transfers are out of scope for the synchronous path. If a subscriber roams, charging still posts to the home shard.

Core mechanism

SQL
-- PostgreSQL 15, checked against the documented UPDATE ... RETURNING semantics
BEGIN;

UPDATE prepaid_account
SET balance_cents = balance_cents - :amount_cents,
    version = version + 1,
    updated_at = now()
WHERE subscriber_id = :subscriber_id
  AND balance_cents >= :amount_cents
RETURNING balance_cents;
-- Zero rows returned means either the account does not exist or funds are insufficient.
-- Distinguish with a follow-up SELECT; never retry the deduction blindly.

INSERT INTO balance_ledger (
    idempotency_key, subscriber_id, country_code, currency,
    amount_cents, balance_after_cents, kind, reference_id, created_at
) VALUES (
    :idempotency_key, :subscriber_id, :country, :currency,
    -:amount_cents, :new_balance, 'DEDUCTION', :reference_id, now()
) ON CONFLICT (idempotency_key) DO NOTHING;

COMMIT;

The WHERE balance_cents >= :amount_cents clause is the whole correctness argument. The row lock taken by the update serialises concurrent deductions for that subscriber, and the predicate is evaluated against the latest committed balance. Two requests for 700 against a balance of 1,000 cannot both pass.

TimeRequest A (700)Request B (700)Committed balance
t0reads balance 1,000reads balance 1,0001,000
t1UPDATE locks row, predicate passes, writes 300UPDATE blocks on row lock1,000
t2inserts ledger entry, commitsunblocks, predicate re-evaluated: 300 >= 700 is false, zero rows300
t3returns 200, balance 300returns 402 insufficient_funds, no ledger entry300

Why not the alternatives

ApproachVerdictReason
Read, check in app code, write backRejectCheck-then-act race. The trace above double-spends.
Optimistic locking with version and retry loopViable, worse fitCorrect, but under contention on a hot subscriber (a shared family plan, a reseller account) retries multiply latency and can livelock. The conditional update fails fast with a clean 402.
Redis Lua script for the deductionReject as source of truthFast, but Redis is not the audit record and failover can lose acknowledged writes. Useful as a read cache for balance display, never as the ledger.
SELECT ... FOR UPDATE then updateAcceptableEquivalent correctness. I prefer the single conditional update because it is one round trip and the failure case is explicit.

Scale and multi-country shape

Top-up / deduction API Country router by subscriber home country Country shard: account + ledger Read replica for balance queries Ledger stream to warehouse and reconciliation

Partition by country first, then hash by subscriber within the country. That matches data residency rules in markets such as Mexico and Brazil, keeps a subscriber's data in one jurisdiction, and avoids distributed transactions. A shard sized for, say, 5,000 writes per second per primary with a pool of 40 connections keeps p99 deduction latency in the 20 to 60 ms range in my experience with this shape; beyond that, split the shard by subscriber hash range rather than adding connections. Balance reads for display can go to a replica or a short-TTL cache, with the response labelled as of a timestamp. Deductions never read from a replica.

Currency is stored on the account and the ledger row. A top-up paid in a different currency converts once, at the top-up rate, and the ledger records both the tendered amount and the credited amount. No implicit FX conversion happens on the deduction path.

Audit trail and failure modes

The ledger is append-only: no updates, no deletes, one row per accepted movement, with the balance after the movement. Reconciliation is then a check that SUM(amount_cents) per subscriber equals the current balance, run continuously by a job consuming the ledger stream. A mismatch pages the on-call team because it means a bug or a manual database edit, not a race.

Three failure modes I would name in the interview:

  1. Timeout after commit. The client never learns the outcome and retries. The retry carries the same Idempotency-Key; the unique constraint on that column returns the original ledger entry and balance instead of applying the movement twice. Keys are retained for at least 7 days, longer than any client retry window.
  2. Shard unavailable. The API returns 503 and the client queues the request. It never falls back to a cache or another country shard, because that is exactly how a balance goes negative.
  3. Deadlock between account and ledger writes. Keep a fixed lock order (account row first, ledger insert second) and retry the whole transaction once on deadlock detection, with the same idempotency key so the retry is safe.

Manual adjustments by support staff go through the same endpoint with kind = ADJUSTMENT and a mandatory reason code, so the audit trail distinguishes customer money movement from operator correction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19How would you implement idempotency for a top-up API in a prepaid mobile system so that retrying the same request does not apply the balance multiple times?

Reported in Senior Software Engineer, BSS/OSS Platforms interview at America Movil

The 90-second answer

The client creates an Idempotency-Key (a UUID) when the top-up intent is created, not when the HTTP call is sent, and sends it on every retry. The server stores that key in the same database transaction that credits the balance and writes the ledger entry, protected by a unique constraint. A retry then finds the completed record and replays the original response instead of crediting again. A cache alone is not enough, because the credit and the key must succeed or fail together.

Assumptions I would state first: the top-up is POST /topups with msisdn, amount_minor, currency, and channel (USSD, app, dealer POS). The balance lives in a prepaid charging store, often Oracle or PostgreSQL in BSS estates, and every credit must be auditable for reconciliation and regulator reporting. Retries come from the client, a gateway, or a dealer terminal on a flaky 2G/3G link, so timeouts after commit are the normal case, not an edge case.

Mechanism

Scope the key to the subscriber and the intent: UNIQUE(msisdn, idempotency_key). Store a hash of the canonical payload (amount, currency, channel) beside the key. On a repeat with the same hash, replay. On a repeat with a different hash, reject with 422 and code: idempotency_key_reuse, because the client has reused a key for a different top-up and replaying would hide a bug.

SQL
CREATE TABLE topup (
  id              NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  msisdn          VARCHAR2(20) NOT NULL,
  idempotency_key VARCHAR2(64) NOT NULL,
  payload_hash    VARCHAR2(64) NOT NULL,
  amount_minor    NUMBER(12) NOT NULL CHECK (amount_minor > 0),
  currency        CHAR(3) NOT NULL,
  status          VARCHAR2(16) NOT NULL, -- PENDING, COMPLETED, FAILED
  response_body   CLOB,
  created_at      TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
  completed_at    TIMESTAMP,
  CONSTRAINT uq_topup_key UNIQUE (msisdn, idempotency_key)
);

The credit path runs in one transaction. Insert the PENDING row first and commit it, so a concurrent duplicate blocks on the unique constraint rather than racing the balance update. Then update the balance with an atomic increment and insert the ledger row, then mark COMPLETED with the response body. If the process dies between the pending insert and completion, a sweeper finds stale PENDING rows and either completes them from the ledger or marks them FAILED, so a later retry with the same key gets a definite answer instead of hanging.

Java
// Spring, checked against Spring Boot 3.2 / Java 17
@Transactional
public TopupResult topUp(String msisdn, String key, TopupRequest req) {
  String hash = sha256(req.canonical());
  try {
    topupRepo.insertPending(msisdn, key, hash, req.amountMinor(), req.currency());
  } catch (DataIntegrityViolationException dup) {
    Topup existing = topupRepo.findByMsisdnAndKey(msisdn, key).orElseThrow();
    if (!existing.payloadHash().equals(hash)) throw new KeyReuseException();
    return existing.toResult(); // replay, no new credit
  }
  balanceRepo.credit(msisdn, req.amountMinor()); // UPDATE ... SET balance = balance + :amt
  ledgerRepo.insert(msisdn, req.amountMinor(), key);
  return topupRepo.markCompleted(msisdn, key, balanceRepo.current(msisdn));
}
unique violation yes no inserted POST /topups + Idempotency-Key Insert PENDING row Load existing row Payload hash matches? Replay stored response 422 key reuse Credit balance + ledger row Mark COMPLETED + store response Return 201 with topup id

Worked trace

TimeEventResult
10:00:00.000Dealer terminal sends key k1, 100 MXNPENDING inserted, balance 500 to 600, COMPLETED, returns 201 topup=881
10:00:02.000Same terminal retries k1 after timeout, same payloadUnique violation, loads topup=881, returns 201 topup=881, balance stays 600
10:00:03.000Two retries arrive concurrentlyOne inserts, the other blocks then replays, single credit
10:00:04.000Client reuses k1 for 200 MXNHash mismatch, 422 idempotency_key_reuse, no credit
10:00:05.000Server crashes after credit, before responseRetry finds PENDING or COMPLETED row, sweeper reconciles from ledger, client gets the original outcome

Trade-offs and failure modes

Redis SETNX with a TTL is faster and fine as a fast path, but on its own it splits the key from the credit across two systems. A crash between them leaves a key with no credit or a credit with no key, and eviction can silently drop the record. I keep the database as the source of truth and use Redis only to short-circuit obvious replays. Retention matters: keep keys for at least 24 to 72 hours, longer than the longest client retry window and the dealer batch cycle, then archive to the ledger store. Deleting them early reopens double credit for a very late retry.

Missing key handling is a contract decision. For money movement I require the header and return 400 idempotency_key_required when it is absent, rather than generating one server side, because a server generated key cannot distinguish a retry from a new intent. For channels that cannot send headers, such as legacy USSD, the gateway generates and persists the key per session and per amount step before calling the API, and that mapping is stored with the session.

Detection in production: alert on the rate of idempotency_key_reuse (client bug), on PENDING rows older than 60 seconds (stuck transaction or sweeper lag), and on ledger totals that differ from the sum of COMPLETED top-ups per msisdn per day. A nightly reconciliation job comparing balance movements to ledger entries catches the case where a credit landed without a completed top-up row, which is the failure that actually costs money.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20Tell us about a time you had to work with a product manager and an architecture team to balance business needs and technical constraints on an integration project?

Reported in Senior Software Engineer, BSS/OSS Platforms interview at America Movil

The 90-second answer

I worked on integrating prepaid eSIM activation between our CRM, the charging platform, and the OSS provisioning system for a retail launch in Mexico and Colombia. The product manager needed activation confirmed in under 5 seconds at the point of sale, because the old SIM process took 20 minutes and stores were losing sales. The architecture team said the provisioning API was synchronous, backed by Oracle, and already ran at a p99 of 800 ms per call with a hard limit of 200 concurrent sessions per country. If we put retail traffic straight on it, we would saturate it during the lunch peak.

We did not pick one side. We split the flow into a synchronous reservation and an asynchronous activation, and we phased the launch by country so we could prove the numbers before scaling.

What we shipped

The store calls CRM to reserve the subscriber profile and check identity documents. CRM calls charging to create a zero-balance wallet and apply the promotional data pack. Only then does it call OSS to provision the eSIM profile. The customer sees "reserved, activating" within 2 seconds, and the store can hand over the device once provisioning confirms, typically 6 to 10 seconds later. If provisioning fails, the wallet reservation is released automatically and the store gets a clear retry code instead of a half-activated line.

Retail POS CRM reserve profile Charging create wallet OSS provision eSIM Callback to CRM POS confirms to customer Compensation release wallet

The latency budget made the trade-off concrete. Hypothetical but measured in staging with production-like Oracle data: CRM reserve 300 ms p99, charging wallet 400 ms p99, OSS provision 800 ms p99. Run sequentially, that is 1.5 seconds before queueing, which fits the 5 second target only if OSS is not saturated. At 200 concurrent sessions and an average provision time of 800 ms, the ceiling is roughly 250 provisions per second per country. Our forecast for launch day was 90 per second at peak in Mexico, so we had headroom, but only if we blocked duplicate submissions.

The negotiation

AskConstraintDecision
Product: instant confirmationOSS p99 800 ms, 200 sessionsShow reserved state in 2 s, confirm async
Architecture: no new synchronous chainCharging timeout 2 s, retries commonIdempotency-Key on every step, 24 h replay
Product: launch both countries at onceData residency, different KYC rulesMexico first, Colombia 3 weeks later after audit
Architecture: protect existing BSSBatch mediation runs nightlyNo direct DB writes, API only, rate limit 150/s

The product manager pushed for a single synchronous call so the POS code stayed simple. I showed the failure trace: if OSS timed out after 2 seconds, the POS would retry, create a second wallet, and billing would charge the customer twice for the pack. With an idempotency key, the retry returns the original wallet ID. That changed the discussion from speed to correctness, and the manager accepted the async confirmation screen.

The architecture team pushed for a full event-driven redesign with Kafka topics for every step. That was the right long-term shape, but it would have taken a quarter to add schema governance, dead-letter handling, and exactly-once semantics across three vendors. We used a transactional outbox in CRM and a single callback topic for provisioning results. It gave us ordering per subscriber without rebuilding the charging platform.

Failure modes we designed for

Provisioning succeeded but the callback was lost. CRM polls OSS by activation ID after 30 seconds if no callback arrives, and the poll is idempotent. Charging wallet created but CRM crashed before calling OSS. A nightly reconciliation job compares wallets in RESERVED state older than 15 minutes against OSS and releases them, with an alert if more than 0.1% are stuck. Duplicate POS submission from a double tap. The POS generates the idempotency key per sale, not per tap, so the second tap replays the first response.

Outcome

Mexico launched with a 98.7% first-attempt activation rate in the first week and a p95 customer wait of 8 seconds. Colombia followed after we fixed a KYC document check that added 600 ms p99 in their CRM instance. The incident I remember most was not a crash. It was a store in Guadalajara retrying because staff did not trust the "activating" screen. We added a printed receipt with a short code the customer could check by SMS, and retries dropped by half. That was the product lesson I took forward: when you move confirmation async for technical reasons, you still owe the user a synchronous piece of certainty.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21Design and implement an API to manage non-overlapping time ranges for customer promotions, with operations to add a range, remove a range, and query whether a given range is fully covered?

Reported in Senior Backend Software Engineer – Billing & Charging Systems interview at America Movil

The 90-second answer

I would model each promotion as a set of disjoint, half-open intervals [start, end) scoped to one customer and one promotion id. Half-open matters: a promo ending at 10:00 and another starting at 10:00 do not overlap, and merging adjacent intervals keeps the set canonical. The invariant is that stored intervals never overlap and never touch, because touching ones would have been merged on insert.

The API is three operations on that set, plus a read to inspect it:

OperationEndpointSemantics
AddPUT /promotions/{id}/intervals body {start, end}Merge with any overlapping or adjacent intervals. Idempotent.
RemoveDELETE /promotions/{id}/intervals?start=...&end=...Subtract the range, splitting an interval if it cuts the middle. Idempotent.
Query coverageGET /promotions/{id}/coverage?start=...&end=...200 {"fullyCovered": true} only if every instant in [start, end) is inside some stored interval.
ListGET /promotions/{id}/intervalsSorted list, for reconciliation and debugging.

Validation is 400 for end <= start or malformed timestamps, 404 for an unknown promotion id, and 409 if a client supplies an If-Match version that no longer matches. Timestamps go over the wire as ISO-8601 UTC strings and are stored as TIMESTAMP WITH TIME ZONE in Oracle, which is what our billing systems already use.

In-memory core

For a single promotion the intervals fit in a TreeMap<Instant, Instant> keyed by start. That gives O(log n) to find the interval that could overlap a query point, and O(log n + k) for add, remove, and coverage where k is the number of intervals touched. A promotion typically has tens of intervals, not millions, so this beats a general interval tree on simplicity and cache behaviour. If one promotion ever reached hundreds of thousands of intervals I would revisit, but the API contract would not change.

Java
// Java 17. Intervals are half-open [start, end), disjoint and non-adjacent.
public final class IntervalSet {
    private final TreeMap<Instant, Instant> map = new TreeMap<>();

    public void add(Instant start, Instant end) {
        if (!start.isBefore(end)) throw new IllegalArgumentException("end must be after start");
        Instant s = start, e = end;
        // Interval that starts at or before start and ends at or after start.
        Map.Entry<Instant, Instant> floor = map.floorEntry(start);
        if (floor != null && !floor.getValue().isBefore(start)) {
            s = floor.getKey();
            e = max(e, floor.getValue());
            map.remove(floor.getKey());
        }
        // Merge every interval that overlaps or touches [s, e).
        while (true) {
            Map.Entry<Instant, Instant> next = map.ceilingEntry(s);
            if (next == null || next.getKey().isAfter(e)) break;
            e = max(e, next.getValue());
            map.remove(next.getKey());
        }
        map.put(s, e);
    }

    public void remove(Instant start, Instant end) {
        if (!start.isBefore(end)) throw new IllegalArgumentException("end must be after start");
        Map.Entry<Instant, Instant> floor = map.floorEntry(start);
        if (floor != null && floor.getValue().isAfter(start)) {
            Instant s = floor.getKey(), oldEnd = floor.getValue();
            map.remove(s);
            if (s.isBefore(start)) map.put(s, start);          // left piece
            if (oldEnd.isAfter(end)) map.put(end, oldEnd);    // right piece, splits middle
        }
        // Drop intervals fully inside, trim one that starts inside and ends after.
        Iterator<Map.Entry<Instant, Instant>> it = map.tailMap(start).entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Instant, Instant> cur = it.next();
            if (!cur.getKey().isBefore(end)) break;
            it.remove();
            if (cur.getValue().isAfter(end)) { map.put(end, cur.getValue()); break; }
        }
    }

    public boolean fullyCovered(Instant start, Instant end) {
        if (!start.isBefore(end)) throw new IllegalArgumentException("end must be after start");
        Instant cursor = start;
        Map.Entry<Instant, Instant> cur = map.floorEntry(start);
        if (cur == null || cur.getValue().isAfter(start) == false) return false;
        cursor = cur.getValue();
        while (cursor.isBefore(end)) {
            Map.Entry<Instant, Instant> next = map.ceilingEntry(cursor);
            if (next == null || next.getKey().isAfter(cursor)) return false; // gap
            cursor = next.getValue();
        }
        return true;
    }
    private static Instant max(Instant a, Instant b) { return a.isAfter(b) ? a : b; }
}

Worked trace

Times are hours on one day, stored as instants.

StepCallStored intervals afterWhy
1add [10,12)[10,12)Empty set.
2add [14,16)[10,12) [14,16)No overlap.
3add [11,15)[10,16)Bridges both, merges into one.
4coverage [10,16)[10,16)Returns true.
5coverage [10,17)[10,16)Returns false, gap after 16.
6remove [12,13)[10,12) [13,16)Splits the middle interval.
7coverage [10,16)[10,12) [13,16)Returns false, gap [12,13).
8add [12,13)[10,16)Adjacent on both sides, merges back.

Step 6 is the case people get wrong. Removing the middle of [10,16) must produce two intervals, and step 8 shows why adjacency merging matters: without it the set would accumulate [10,12) [12,13) [13,16) and coverage checks would still pass but the list endpoint and storage would bloat.

Concurrency and persistence

The TreeMap is not thread safe, so I lock per promotion, not globally. In the service I use a striped lock keyed by promotion id, or a database transaction when the intervals are persisted. With Oracle I keep a parent promotions row and a child promotion_intervals(promotion_id, start_ts, end_ts) table. Oracle has no exclusion constraint to enforce non-overlap declaratively, so the transaction does SELECT ... FOR UPDATE on the parent row first. That serialises writers for one promotion, lets different promotions proceed in parallel, and makes the read-modify-write of the interval set atomic. The parent row also carries a version column returned as the ETag, so a client doing read-modify-write across requests gets a 412 on a stale version instead of silently overwriting a concurrent add.

Failure modes I would name in the loop: a client retrying PUT after a timeout is safe because add is idempotent, merging the same range twice yields the same set. A remove that races an add on the same promotion is serialised by the parent row lock, so the second writer sees the first writer's intervals. Clock skew is handled by rejecting timestamps far in the future at the edge and by storing UTC instants only, never local times, since promotions run across countries in different zones. If the service restarts, intervals are reloaded from Oracle on first access per promotion and cached, so the in-memory structure is a cache, not the source of truth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22Implement a Java method for a simplified rating service that calculates the total charge for a list of voice call records with durationSeconds, countryCode, and isRoaming, applying local, international, and roaming rates and rounding per call to 2 decimal places?

Reported in Backend Software Engineer (Telecom Billing Systems) interview at America Movil

The 90-second answer

I would state the assumptions first, because the rating depends on them. Rates are per minute, billed pro-rata by the second, and roaming takes precedence over international, which takes precedence over local. Each call is rounded to 2 decimal places with HALF_UP before it is added to the total. Money never goes through double, so I use BigDecimal throughout.

Java
// Java 17
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public record CallRecord(long durationSeconds, String countryCode, boolean isRoaming) {}

public final class RatingService {
    private static final BigDecimal SIXTY = new BigDecimal("60");
    private static final Map<String, BigDecimal> RATE_PER_MINUTE = Map.of(
        "LOCAL", new BigDecimal("0.05"),
        "INTERNATIONAL", new BigDecimal("0.25"),
        "ROAMING", new BigDecimal("0.60")
    );
    private final String homeCountry;

    public RatingService(String homeCountry) { this.homeCountry = homeCountry; }

    public BigDecimal totalCharge(List<CallRecord> calls) {
        Objects.requireNonNull(calls, "calls");
        BigDecimal total = BigDecimal.ZERO;
        for (CallRecord c : calls) {
            if (c.durationSeconds() < 0) {
                throw new IllegalArgumentException("durationSeconds < 0: " + c.durationSeconds());
            }
            String tier = c.isRoaming() ? "ROAMING"
                : c.countryCode().equals(homeCountry) ? "LOCAL" : "INTERNATIONAL";
            BigDecimal rate = RATE_PER_MINUTE.get(tier);
            BigDecimal perCall = new BigDecimal(c.durationSeconds())
                .multiply(rate)
                .divide(SIXTY, 2, RoundingMode.HALF_UP);
            total = total.add(perCall);
        }
        return total.setScale(2, RoundingMode.HALF_UP);
    }
}

The precedence matters. A roaming call to the home country is still roaming, because the subscriber is not on the home network. Checking isRoaming first encodes that. If the business instead wanted international to win over roaming, that is a one-line change, but the order has to be explicit and tested.

Worked trace

Home country MX, rates as above.

CalldurationSecondscountryCodeisRoamingTierCalculationRounded per call
160MXfalseLOCAL60/60 x 0.050.05
290USfalseINTERNATIONAL90/60 x 0.25 = 0.3750.38
330MXtrueROAMING30/60 x 0.60 = 0.300.30
40USfalseINTERNATIONAL00.00

Total: 0.05 + 0.38 + 0.30 + 0.00 = 0.73. Note call 2. Rounding only at the end would give 0.05 + 0.375 + 0.30 = 0.725, which rounds to 0.73 here by coincidence, but with many calls the two policies diverge. Per-call rounding matches how CDR rating usually appears on an invoice, line by line, and it is what the question asks for.

Failure modes I would call out

double is the classic trap. 0.1 + 0.2 is not 0.3 in binary floating point, and a billing total that drifts by a cent per thousand calls will fail reconciliation. BigDecimal constructed from a string, as above, avoids that. Constructing it from a double reintroduces the error.

Nulls and bad data need a decision, not an accident. A null countryCode will throw NullPointerException on equals, which is arguably correct for a rating job, since silently treating it as local would undercharge. A negative duration is rejected explicitly. In production I would also expect a missing rate for a new country or tier to fail loudly rather than default to zero, because a zero rate hides a configuration gap as free calls.

Two follow-ups an interviewer often probes. First, minimum billing: many carriers bill a minimum of 60 seconds per call, or round duration up to the next minute. That changes the formula to ceil(durationSeconds / 60) * rate, and I would ask which policy applies before coding it. Second, scale: this method is O(n) time and O(1) extra space, which is fine for a batch of CDRs. If the input were tens of millions of records streamed from a switch, I would move to a streaming pipeline that applies the same per-call rounding in a map step and sums with BigDecimal in the reduce step, rather than loading the whole list into memory.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23Given tables subscribers, subscriptions, usage_records, and plans, write an SQL query to return, for the current month, each active subscriber's total data used and whether they have exceeded their quota?

Reported in Backend Software Engineer (Telecom Billing Systems) interview at America Movil

The 90-second answer

I would state my assumptions first, because the tables as named do not fix three things that change the query: what marks a subscriber active, what marks a subscription current, and what unit the quota uses. I will assume subscribers.status = 'ACTIVE', one current row in subscriptions per subscriber with start_date and end_date, plans.data_quota_bytes in bytes, and usage_records.recorded_at as a timestamp. If your schema differs, only the predicates change.

SQL
-- PostgreSQL 15. Adjust date_trunc if you are on Oracle.
WITH usage_this_month AS (
    SELECT subscriber_id,
           SUM(bytes_used) AS total_bytes
    FROM usage_records
    WHERE recorded_at >= date_trunc('month', CURRENT_DATE)
      AND recorded_at <  date_trunc('month', CURRENT_DATE) + INTERVAL '1 month'
    GROUP BY subscriber_id
)
SELECT s.id AS subscriber_id,
       p.name AS plan_name,
       p.data_quota_bytes,
       COALESCE(u.total_bytes, 0) AS total_data_used_bytes,
       COALESCE(u.total_bytes, 0) > p.data_quota_bytes AS quota_exceeded
FROM subscribers s
JOIN subscriptions sub
  ON sub.subscriber_id = s.id
 AND sub.status = 'ACTIVE'
 AND CURRENT_DATE >= sub.start_date
 AND (sub.end_date IS NULL OR CURRENT_DATE <= sub.end_date)
JOIN plans p
  ON p.id = sub.plan_id
LEFT JOIN usage_this_month u
  ON u.subscriber_id = s.id
WHERE s.status = 'ACTIVE';

Three choices in that query do the real work. The usage aggregation is a separate CTE, so joining usage_records directly cannot multiply rows if a subscriber somehow has two subscription rows. The LEFT JOIN keeps subscribers with no usage this month at zero instead of dropping them. The month filter is a half-open range, >= month start and < next month start, which can use an index and does not break on timestamps with a time component the way MONTH(recorded_at) = MONTH(CURRENT_DATE) does.

Worked trace

Suppose the month is May 2026, plan P10 has a quota of 10,000,000,000 bytes, and usage is:

subscriber_idstatusplanusage in May (bytes)total_data_used_bytesquota_exceeded
101ACTIVEP104,200,000,000 + 3,100,000,0007,300,000,000false
102ACTIVEP1011,500,000,00011,500,000,000true
103ACTIVEP10none0false
104SUSPENDEDP1099,000,000,000excluded by WHERE s.status = 'ACTIVE'excluded

Subscriber 103 is the case people miss in interviews. An inner join to usage_records silently removes every subscriber who used no data, which is exactly the population billing wants to see at zero.

What I would add before calling it production ready

Index the access paths the query actually uses:

SQL
CREATE INDEX idx_usage_subscriber_time
    ON usage_records (subscriber_id, recorded_at)
    INCLUDE (bytes_used);

CREATE INDEX idx_subscriptions_subscriber_status
    ON subscriptions (subscriber_id, status, start_date, end_date);

Without the first index, the CTE scans the whole month of usage records. At América Móvil scale, say 50 million records a month across countries, that scan is the difference between a report that runs in seconds and one that times out. With it, the database can aggregate per subscriber using the index.

Two failure modes I would name. First, duplicate ingestion. If the same CDR or usage record lands twice from a network element, SUM double counts and subscribers appear over quota. The query cannot fix that. You need a unique key on the source record id in usage_records and deduplication at ingest. Second, timezone. CURRENT_DATE and recorded_at must be in the same zone. If recorded_at is stored in UTC and the billing month is local time in Mexico City, Bogotá, or Santiago, records near midnight on the first of the month land in the wrong month. I would store UTC and convert the month boundary to UTC explicitly, or store a local billing date column.

One limit to state out loud: this compares against the full monthly quota. If a subscriber changed plan mid-month, a correct billing answer needs prorated quota, which this query does not do. I would flag that rather than pretend a single plans.data_quota_bytes covers it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24How would you integrate a new microservice-based billing component with existing legacy systems (e.g., COBOL/mainframe and SOAP web services) at América Móvil while minimizing risk?

Reported in Backend Software Engineer (Telecom Billing Systems) interview at America Movil

The 90-second answer

I would not rewrite the mainframe or call it directly from the new service. I would put an anti-corruption layer between them, run the new billing component in shadow mode first, then shift traffic in small slices with reconciliation at every step.

The legacy system stays the system of record until the new component proves it can reproduce its charges. That ordering matters because a billing error is not a failed request you can retry. It is money taken from a subscriber, or revenue lost, and it surfaces weeks later in disputes and audits.

How I would sequence it

First, map the contracts. The COBOL side usually exposes batch files and a SOAP facade with fixed-width or positional fields, no versioning, and timeouts measured in seconds. I would document the exact fields for a rating request, the rounding rule per call, and what the mainframe returns on a partial failure. In telecom billing, rounding per CDR to two decimals versus rounding the daily total can differ by cents per subscriber, which becomes material at Telcel or Claro scale.

Second, build the adapter. The microservice talks REST or events internally. The adapter translates to SOAP, sets timeouts, and enforces idempotency, because the mainframe will not do it for you.

Java
// Java 17, Spring Boot 3 adapter. Checked against the SOAP contract, not the WSDL alone.
public class LegacyRatingAdapter implements RatingPort {
    private final SoapClient soap;
    private final IdempotencyStore store;

    public RatingResult rate(RatingRequest req) {
        // Keyed on subscriber + CDR id + rating date, stored before the call.
        return store.executeOnce(req.idempotencyKey(), () -> {
            var soapReq = LegacyMapper.toSoap(req); // fixed fields, explicit rounding mode
            try {
                var resp = soap.call("RateCall", soapReq, Duration.ofSeconds(5));
                return LegacyMapper.fromSoap(resp);
            } catch (SoapFault f) {
                throw new TransientBillingException(f.code(), f);
            }
        });
    }
}

A retry after a timeout is the classic trap. The mainframe may have rated and debited the call, then the response is lost. Without the stored key, the retry rates it again. With it, the second call replays the first result.

Third, shadow and dual-run. The new component receives a copy of live CDRs, rates them, and writes to a comparison table. It does not debit anything. I would run this for at least one full billing cycle, including month-end, because peak roaming and promotional rules rarely appear in a normal week.

CDR stream New billing service Legacy rating via SOAP Anti-corruption adapter Reconciliation job Alert on mismatch

Reconciliation as the gate

PhaseTraffic to new serviceExit criterion
Shadow100% copied, 0% authoritativeMismatch under 0.01% of CDRs for 14 days, every mismatch explained
Canary by segment1% of subscribers, one country, non-roaming voice onlyNo balance disputes, p99 adapter latency under 800 ms
Expand10%, then 50%, adding roaming and dataReconciliation clean across a month-end close
Cutover100%Legacy kept read-only for one cycle for audit queries

Those figures are the kind I would agree with finance and operations before starting, not after. A mismatch rate of 0.01% on a hypothetical 12 million CDRs a day is still 1,200 records a day, so each one needs a reason code: rounding, tariff table version, timezone for the rating date, or a field the mapper dropped.

Failure modes I would name in the interview

Batch versus online mismatch. The mainframe may rate in nightly batches with tariff tables loaded at midnight. If the microservice loads a new tariff at 00:01 in a different timezone, shadow results diverge for an hour. I would pin the tariff version to the CDR timestamp and log it with every rating.

SOAP timeouts under load. A 5 second timeout that works at 200 requests per second can collapse at peak if the mainframe queue backs up. I would set a circuit breaker per operation, shed to the legacy path, and alert on breaker opens rather than letting threads pile up.

Schema drift in the facade. SOAP services in this estate often add optional fields without a version bump. The adapter should ignore unknown fields, fail loudly on missing required ones, and contract-test against recorded production payloads.

Rollback. A feature flag per country and per call type lets me send roaming traffic back to legacy without redeploying. Rollback is a routing change, not a code fix, and I would rehearse it before the canary.

The point of the sequence is that at no stage does a subscriber balance depend on an unproven component. The mainframe keeps charging until the numbers match, and the adapter keeps the new service from inheriting the legacy system's quirks as its own internal model.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25Explain how you would design a scalable system to handle millions of users simultaneously?

Reported in Software Engineer interview at America Movil

The 90-second answer

I would start by pinning down what "millions simultaneously" means, because the design changes completely between 1 million registered users and 1 million concurrent connections. My working assumptions, stated up front: 5 million concurrent users, 20% making a request in any given minute, peak traffic 3x average, reads dominating writes 10:1, and p99 under 200 ms for reads. If the interviewer wants writes or real-time push instead, I would say so and adjust.

The shape is boring on purpose: stateless application tier behind a load balancer, cache in front of the database, writes queued where they do not need an immediate answer, and the database sharded by a stable key before it becomes the bottleneck.

Mobile and web clients CDN and WAF Load balancer Stateless API pods Redis cache Shard router PostgreSQL shards Kafka queue Async workers

Capacity, with real numbers

Hypothetical but checkable: 5 million concurrent users, 20% active per minute gives 1 million requests per minute, or about 16,700 requests per second on average. At 3x peak that is 50,000 rps. If a request costs 5 ms of CPU on the application tier and I target 70% utilisation, I need 50,000 x 0.005 / 0.7, roughly 360 cores, so about 45 pods at 8 cores each. That is the number I would autoscale against, not CPU alone. I would also scale on queue depth and p99 latency, because CPU lags when requests block on the database.

For connections, 5 million concurrent WebSocket or long-poll connections cannot sit on the same tier as 50,000 rps of short requests. I would split them: short HTTP on the API pods, persistent connections on a separate gateway tier sized by connections per node (for example 50,000 idle connections per node at 2 GB RAM, labelled as a sizing assumption to validate with a load test), with presence state in Redis rather than in process memory.

Where it breaks, in order

LayerFirst bottleneckFix I would reach forWhen not to use it
Load balancerConnection churn, TLS costTerminate TLS at the edge, keep-alive, multiple AZsSingle region only if data residency forces it
Application tierStateful sessionsStateless pods, session data in Redis with a TTLNever pin users to pods except for the gateway tier
CacheHot keys, stampede on expiryRequest coalescing, jittered TTLs, cache-asideDo not cache balances or anything needing strong consistency
DatabaseSingle primary write limitRead replicas for reads, shard by subscriber or tenant ID for writesSharding before you need it, it makes cross-shard queries painful
QueueUnbounded backlog during a spikeBounded queue, backpressure, dead-letter topic, drop low-priority work firstSynchronous path for notifications, emails, CDR-style event ingestion

Shard routing, the part people hand-wave

For a telecom workload at América Móvil, the natural shard key is subscriber ID, because most queries are "give me this subscriber's data" and that keeps a subscriber's records on one shard. Cross-subscriber analytics then go to a separate warehouse fed from the queue, not to the operational shards.

Java
// Java 17, routing only. Hash is stable across JVM restarts.
public int shardFor(String subscriberId, int shardCount) {
    long h = 0;
    for (char c : subscriberId.toCharArray()) {
        h = 31 * h + c;
    }
    return (int) Math.floorMod(h, shardCount);
}

I would use a proper hash function in production and a lookup table for shard ranges so I can rebalance by moving ranges instead of rehashing every key. Resharding is the failure mode I would call out: plan for it with a dual-write or backfill period, or the first rebalance becomes an outage.

Failure modes I would name without being asked

Cache stampede when a hot key expires and 10,000 requests hit the database at once. Mitigation is single-flight loading plus jitter, and I would detect it from database connections spiking while application CPU stays flat.

Retry storms. A client timeout at 2 seconds with aggressive retries can double load exactly when the system is already saturated. Mitigation is exponential backoff with jitter on the client, a server-side deadline, and idempotency keys on writes so a retry does not create a duplicate top-up or order.

One AZ failing. With pods spread across three availability zones and the load balancer health-checking them, losing one AZ costs a third of capacity. My autoscaling headroom has to absorb that, which is why I target 70% utilisation rather than 95%.

What I would not do

I would not start with Kubernetes for its own sake, and I would not shard on day one. I would start with a load-balanced stateless tier, a cache, read replicas, and a queue, measure where p99 actually degrades under a load test at 2x expected peak, and shard only the store that saturates. That sequence keeps the system operable by a small team, which matters more than theoretical scale.

Curated: · Written: · Reviewed:

Difficulty: Medium

Curated: · Written: · Reviewed: