Tencent interview questions & answers

20 real Tencent interview questions with full model answers — System design, Coding, Technical, Product & growth. Drawn from the same verified bank ChannelPulse drills from (59 Tencent questions in total).

BehavioralMediumTencentBackend EngineerSecond Round

1. What was the most challenging task you worked on, what difficulties did you encounter, and how did you solve them?

Model answer

  1. Situation — One of the most challenging projects I owned was improving the reliability of a high-traffic backend service that processed user actions asynchronously. During peak periods, queue lag grew, requests became slower, and retries sometimes amplified the load. The service supported a user-facing feature, so delays and duplicate processing were visible to customers and could affect downstream systems.
  2. Task — I was responsible for finding the main bottlenecks and leading a safe improvement without interrupting traffic. The main tension was that we needed to reduce latency quickly while preserving ordering and preventing duplicate side effects.
  3. Action
  • I first added tracing and broke down latency by API handling, queue wait, and worker processing. That showed the largest issue was uneven work distribution and a growing retry backlog, rather than the database alone.
  • I worked with the team to agree on service-level indicators and a rollback plan before changing the consumer. This kept the discussion focused on measurable outcomes rather than competing guesses.
  • I introduced bounded retries with exponential backoff and a dead-letter path for messages that repeatedly failed. I also made the handler idempotent using a stable event identifier, so a retry could not apply the same business change twice.
  • I changed worker scaling to respond to queue age as well as queue depth. Queue age better reflected customer impact when message sizes and processing times varied.
  • I validated the changes with replay tests and a staged rollout, checking ordering, duplicate rates, error rates, and downstream database load at each step. When a metric regressed, I paused the rollout and adjusted the concurrency limit rather than pushing through.
  1. Result — Queue lag and peak processing latency fell substantially, and duplicate side effects became rare and observable rather than silently corrupting state. The team also gained clearer dashboards and a repeatable rollout process. I learned to treat retries as part of the system’s load model, not merely as a reliability feature; making them bounded and observable was as important as adding capacity.
BehavioralMediumTencentFrontend EngineerThird Interview

2. Why did you create your mini-program?

Model answer

  1. Situation — I noticed that students were finding campus events through scattered group-chat messages and posters. Details were easy to miss, organizers had to collect registrations manually, and students often had to ask the same questions about time, location, or remaining capacity. I was working with a campus club and saw an opportunity to solve that end-to-end problem with a lightweight tool.
  2. Task — I proposed and built a mini-program that made event discovery and registration quick, while keeping the experience accessible to people who would not install a dedicated app. The key constraint was that organizers needed something simple enough to maintain alongside their regular work.
  3. Action
  • I chose a WeChat mini-program because students already used WeChat to discover and share events. A link or QR code could take someone directly to the event without an app-store download.
  • I spoke with organizers and students before defining the first version. Their most frequent needs were event details, a clear registration action, and a way to know whether capacity was available.
  • I kept the MVP focused on an event list, event detail pages, registration, and an organizer workflow for publishing updates. I avoided adding features such as social feeds that would increase implementation and maintenance cost without solving the core problem.
  • I worked with the backend developer to make registration state server-authoritative, so users would not be shown as registered just because they tapped a button while offline or during a failed request.
  • I shared the pilot through club QR codes and collected feedback from users and organizers, then prioritized fixes to confusing details and slow-loading images.
  1. Result — We piloted the mini-program with three student organizations and around 200 users. It gave students a single place to check event information and register, while reducing the organizers’ reliance on manually tracking responses across chats. I learned that choosing a familiar distribution channel mattered as much as the feature set: reducing the effort to reach the product was central to solving the original problem.
BehavioralMediumTencentFrontend EngineerThird Interview

3. What difficulties did you encounter while working on your mini-program?

Model answer

  1. Situation — I built a WeChat mini-program for a campus club to publish events and let students register without installing a separate app. I owned most of the frontend work, coordinating with one backend developer and the club organizers. The main stakes were reliability during registration peaks and keeping the experience simple for users arriving from a shared link.
  2. Task — I needed to make the key flow—open an event, view its details, and register—work consistently across devices and network conditions, while staying within mini-program platform constraints.
  3. Action
  • I first tested the flow on both iOS and Android rather than relying only on the developer tools. That exposed differences in permission prompts, navigation behavior, and how some devices handled image sizing.
  • I found that event details could be opened before their data had loaded. I added explicit loading, empty, and error states, and made registration depend on the server’s response rather than optimistic UI alone.
  • I handled slow connections by compressing event images, avoiding duplicate requests when users navigated back and forth, and keeping the initial page focused on the information needed to decide whether to register.
  • I also had to work around lifecycle and platform API differences. I centralized request and authorization handling instead of scattering platform checks throughout page components, which made the behavior easier to test and change.
  • When a platform behavior was unclear, I reproduced it in a small test page and documented the result for the backend developer and organizers, so we could agree on the expected user experience before release.
  1. Result — We shipped the mini-program for a pilot with three student organizations and around 200 users. The core registration flow worked across the devices we tested, and the explicit loading and error states reduced confusion when requests were slow. I learned to treat the mini-program runtime as its own platform, not simply as a small web page, and to test real-device behavior early.
BehavioralMediumTencentFrontend EngineerThird Interview

4. How would you handle a situation where it is difficult to distinguish between front-end and back-end requirements?

Model answer

  1. Situation — I have encountered features where the user’s visible behavior seemed straightforward, but the frontend and backend teams had different assumptions about validation, permissions, and failure handling. That ambiguity can result in mismatched API contracts, duplicated logic, or a UI that looks successful even though the operation failed.
  2. Task — My responsibility was to help turn the product goal into a clear, testable contract, while making sure we placed each responsibility in the layer best suited to own it.
  3. Action
  • I first restated the user journey and asked product and design to clarify expected behavior, including empty, loading, success, error, and permission-denied states.
  • I wrote down unresolved questions as concrete examples. For instance: if a user submits an expired item, should the server reject it, and what message and recovery action should the interface show?
  • I brought frontend and backend engineers together to agree on the API shape, field meanings, validation ownership, error codes, and compatibility expectations before parallel implementation began.
  • I advocated for authoritative business rules and security checks on the backend, with frontend validation used for fast feedback and usability—not as a substitute for server enforcement.
  • I proposed a small contract example and test cases, then used a mock response or API stub to unblock frontend work while the service was being built.
  • As implementation progressed, I checked the actual response behavior against the agreed contract and updated documentation when a legitimate product decision changed.
  1. Result — We avoided building against incompatible assumptions and made the resulting interaction more predictable, including its error and recovery paths. The key lesson for me is that front-end versus back-end ownership is not something to resolve by defending a territory. I start from the user outcome, make assumptions explicit, assign each rule to the right layer, and keep both teams aligned through a concrete contract.
BehavioralMediumTencentFrontend EngineerThird Interview

5. Which areas of front-end development do you prefer?

Model answer

  1. Situation — The areas I enjoy most are building reusable interface foundations and improving the quality of real user interactions. In one project, several teams were implementing similar controls independently, while users experienced inconsistent behavior across related screens.
  2. Task — I took responsibility for improving consistency without slowing feature teams down or forcing every use case into an inflexible component library.
  3. Action
  • I started by studying the repeated patterns and talking with designers and engineers to understand which differences were intentional and which were accidental.
  • I focused on components with broad value—such as form controls, dialogs, and loading and error states—and defined clear APIs, sensible defaults, and documented accessibility behavior.
  • I treated performance as part of interface quality. For a complex screen, I used browser profiling to find avoidable rendering work and large assets, then made targeted changes instead of prematurely adding abstractions.
  • I built with responsive layouts, keyboard navigation, and clear feedback states in mind, and added tests for important interaction behavior rather than only checking that components rendered.
  • I invited feedback from feature teams and adjusted the abstractions when real use cases showed that an API was too restrictive.
  1. Result — Teams could deliver related screens more consistently, and we reduced repeated implementation work while preserving room for product-specific behavior. I learned that reusable frontend work succeeds when it makes the common path easy but does not hide important trade-offs. I especially enjoy the combination of craft and engineering judgment: turning user needs into accessible, fast interactions, then creating foundations that help the next feature team do the same. I am also happy to work across the stack when a user-facing issue requires it; my preference is a focus, not a boundary.
BehavioralMediumTencentFrontend EngineerThird Interview

6. Do you regularly gather feedback from users?

Model answer

  1. Situation — Yes. On a product team, I worked on a high-traffic interface where users reported that a key workflow felt confusing, but the initial reports did not explain where people were getting stuck. Since the experience served different user groups, relying only on the team’s assumptions could have led us to fix the wrong thing.
  2. Task — I wanted to make user feedback a regular input to frontend decisions, while balancing direct feedback with behavioral data and delivery time.
  3. Action
  • I set up lightweight ways to hear from users: reviewing support tickets and app-store comments, joining customer interviews when possible, and asking targeted follow-up questions after usability sessions.
  • I paired those comments with product analytics. For example, users said a multi-step submission flow was hard to understand, so I checked step-level drop-off and found that exits clustered at the same transition.
  • I reproduced the flow on different screen sizes and watched users attempt it. That helped distinguish unclear labels from a technical issue with the responsive layout.
  • I summarized the evidence for design and product, proposed a small change to the progress indicator and action labels, and agreed on success and guardrail metrics before implementation.
  • After release, I checked the funnel and solicited follow-up feedback rather than treating launch as the end of the process. I also shared the findings with the team so future designs could benefit.
  1. Result — The revised flow reduced abandonment at that transition and users needed less help completing the task. More importantly, we established a repeatable feedback loop: combine what users say with what they do, validate the cause, and measure the result. I do not assume every request should be implemented literally; I use feedback to understand the underlying need and then test the simplest useful response.
CodingEasyTencentBackend EngineerEighth Round

7. Implement strcpy to copy a string.

Model answer

// Copy a null-terminated byte string, including its '\0' terminator.
// Preconditions: src contains a terminator and dest has sufficient capacity.
function strcpyBytes(dest, src) {
  let length = 0;
  while (length < src.length && src[length] !== 0) {
    length++;
  }

  if (length === src.length) {
    throw new Error('Source is not null-terminated');
  }
  if (dest.length < length + 1) {
    throw new Error('Destination buffer is too small');
  }

  // Copy the characters and the terminating zero.
  for (let i = 0; i <= length; i++) {
    dest[i] = src[i];
  }
  return dest;
}

// Example: encode UTF-8 text and add the C-style null terminator.
const text = new TextEncoder().encode('Tencent');
const src = new Uint8Array(text.length + 1);
src.set(text);
const dest = new Uint8Array(src.length);

strcpyBytes(dest, src);
console.log(new TextDecoder().decode(dest.subarray(0, dest.length - 1)));
  • This models strcpy on byte buffers because JavaScript strings are immutable and are not null-terminated.
  • Like C strcpy, overlapping source and destination buffers are not supported; use a temporary buffer or a memmove-style implementation if overlap must be handled.

Complexity: O(n) time and O(1) extra space, where n is the source length.

CodingEasyTencentGame Developer

8. Reverse an integer using a stack.

Model answer

Use a stack to store the digits, then pop them to construct the reversed value. This version follows the common signed 32-bit integer convention: return 0 if the reversed value overflows.

function reverseInteger(x) {
  if (!Number.isInteger(x)) {
    throw new Error("Input must be an integer");
  }

  const negative = x < 0;
  let remaining = Math.abs(x);
  const stack = [];

  // Push each decimal digit onto the stack.
  while (remaining > 0) {
    stack.push(remaining % 10);
    remaining = Math.floor(remaining / 10);
  }

  // Pop digits to build the reversed number.
  let reversed = 0;
  while (stack.length > 0) {
    reversed = reversed * 10 + stack.pop();
  }

  if (negative) reversed = -reversed;

  // Enforce the signed 32-bit integer range.
  if (reversed < -2147483648 || reversed > 2147483647) {
    return 0;
  }

  return reversed;
}

console.log(reverseInteger(123));  // 321
console.log(reverseInteger(-120)); // -21
  • The sign is saved separately; leading zeroes disappear naturally during number construction.
  • The stack holds one entry per decimal digit.

Complexity: Time O(d), space O(d), where d is the number of digits.

CodingEasyTencentFrontend EngineerFirst Round

9. Write a layout that vertically centers its content.

Model answer

function createVerticallyCenteredLayout(parent = document.body, content = "Centered content") {
  const layout = document.createElement("main");

  // Use flexbox to center the content vertically and horizontally.
  Object.assign(layout.style, {
    minHeight: "100vh",
    display: "flex",
    alignItems: "center",
    justifyContent: "center"
  });

  if (content instanceof Node) {
    layout.appendChild(content);
  } else {
    layout.textContent = String(content);
  }

  parent.appendChild(layout);
  return layout;
}

createVerticallyCenteredLayout();
  • minHeight: 100vh gives the layout at least the viewport height.
  • Flexbox centers the child on both axes; remove justifyContent if only vertical centering is needed.

Complexity: O(1) time and space, excluding the browser’s DOM rendering.

CodingEasyTencentBackend EngineerFirst Round

10. Find the depth of a binary tree.

Model answer

function maxDepth(root) {
  if (root === null) return 0;

  // Each queue entry stores a node and its depth.
  const queue = [[root, 1]];
  let head = 0;
  let depth = 0;

  while (head < queue.length) {
    const [node, nodeDepth] = queue[head++];
    depth = Math.max(depth, nodeDepth);

    if (node.left !== null) queue.push([node.left, nodeDepth + 1]);
    if (node.right !== null) queue.push([node.right, nodeDepth + 1]);
  }

  return depth;
}
  • Use breadth-first traversal and track each node’s depth; the greatest depth is the tree’s maximum depth.
  • Return 0 for an empty tree. This assumes nodes have left and right properties.

Complexity: Time O(n); space O(w), where w is the maximum tree width (worst case O(n)).

CodingMediumTencentBackend EngineerSeventh Round

11. Given n buildings in a row with heights w_i, where 1 ≤ n ≤ 100000 and 1 ≤ w_i ≤ 100000, determine for every building how many buildings Xiao Q can…

The full question

Given n buildings in a row with heights w_i, where 1 ≤ n ≤ 100000 and 1 ≤ w_i ≤ 100000, determine for every building how many buildings Xiao Q can see from that position, including the current building. Xiao Q walks from the first building to the last. A building in front that is at least as tall as a building behind it blocks that building. Read n followed by the n building heights, and output n space-separated visibility counts. For input 6 and heights 5 3 8 3 2 5, the output is 3 3 5 4 4 4.

Model answer

For a building at position i, scan outward independently in each direction. A building is visible if every building between it and i is shorter than it. Thus, in either direction, visible buildings are exactly the strict record highs encountered while scanning outward.

const fs = require("fs");
const tokens = fs.readFileSync(0, "utf8").trim().split(/\s+/).map(Number);
const n = tokens[0];
const heights = tokens.slice(1, n + 1);

if (!Number.isInteger(n) || n <= 0 || heights.length !== n) {
  throw new Error("Expected n followed by n building heights");
}

const nextGreaterRight = Array(n).fill(-1);
const nextGreaterLeft = Array(n).fill(-1);
let stack = [];

// For each building, find the next strictly taller building to its right.
for (let i = n - 1; i >= 0; i--) {
  while (stack.length > 0 && heights[stack[stack.length - 1]] <= heights[i]) {
    stack.pop();
  }
  if (stack.length > 0) nextGreaterRight[i] = stack[stack.length - 1];
  stack.push(i);
}

stack = [];
// For each building, find the next strictly taller building to its left.
for (let i = 0; i < n; i++) {
  while (stack.length > 0 && heights[stack[stack.length - 1]] <= heights[i]) {
    stack.pop();
  }
  if (stack.length > 0) nextGreaterLeft[i] = stack[stack.length - 1];
  stack.push(i);
}

// Count record highs when scanning rightward starting at each index.
const visibleFromStartRight = Array(n).fill(0);
for (let i = n - 1; i >= 0; i--) {
  visibleFromStartRight[i] = 1;
  const next = nextGreaterRight[i];
  if (next !== -1) visibleFromStartRight[i] += visibleFromStartRight[next];
}

// Count record highs when scanning leftward starting at each index.
const visibleFromStartLeft = Array(n).fill(0);
for (let i = 0; i < n; i++) {
  visibleFromStartLeft[i] = 1;
  const next = nextGreaterLeft[i];
  if (next !== -1) visibleFromStartLeft[i] += visibleFromStartLeft[next];
}

const answer = heights.map((_, i) => {
  let count = 1; // Include the current building.
  if (i + 1 < n) count += visibleFromStartRight[i + 1];
  if (i - 1 >= 0) count += visibleFromStartLeft[i - 1];
  return count;
});

console.log(answer.join(" "));
  • The next-strictly-greater links skip buildings blocked by a closer building at least as tall as them. Following those links counts all visible record highs without scanning each position repeatedly.
  • The two directional counts are independent; the current building is included once.
  • Complexity: O(n) time and O(n) space. For the sample, the output is 3 3 5 4 4 4.
CodingMediumTencentBackend EngineerFirst Round

12. How would you implement a hash table?

Model answer

Here is a simple hash table for string keys, using separate chaining to handle collisions and resizing to keep the load factor bounded.

class HashTable {
  constructor(initialCapacity = 8) {
    this.capacity = Math.max(1, initialCapacity);
    this.buckets = Array.from({ length: this.capacity }, () => []);
    this.size = 0;
    this.maxLoadFactor = 0.75;
  }

  // Hash a string into a non-negative 32-bit integer.
  hash(key) {
    if (typeof key !== "string") {
      throw new TypeError("HashTable keys must be strings");
    }

    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash = (Math.imul(hash, 31) + key.charCodeAt(i)) >>> 0;
    }
    return hash % this.capacity;
  }

  set(key, value) {
    const index = this.hash(key);
    const bucket = this.buckets[index];

    // Update an existing key rather than adding a duplicate.
    for (const entry of bucket) {
      if (entry[0] === key) {
        entry[1] = value;
        return this;
      }
    }

    bucket.push([key, value]);
    this.size++;

    if (this.size / this.capacity > this.maxLoadFactor) {
      this.resize(this.capacity * 2);
    }
    return this;
  }

  get(key) {
    const bucket = this.buckets[this.hash(key)];
    for (const [storedKey, value] of bucket) {
      if (storedKey === key) return value;
    }
    return undefined;
  }

  has(key) {
    const bucket = this.buckets[this.hash(key)];
    return bucket.some(([storedKey]) => storedKey === key);
  }

  delete(key) {
    const bucket = this.buckets[this.hash(key)];
    const index = bucket.findIndex(([storedKey]) => storedKey === key);
    if (index === -1) return false;

    bucket.splice(index, 1);
    this.size--;
    return true;
  }

  resize(newCapacity) {
    const oldBuckets = this.buckets;
    this.capacity = newCapacity;
    this.buckets = Array.from({ length: newCapacity }, () => []);

    // Re-hash entries because their bucket indexes depend on capacity.
    for (const bucket of oldBuckets) {
      for (const [key, value] of bucket) {
        this.buckets[this.hash(key)].push([key, value]);
      }
    }
  }
}
  • Separate chaining makes collisions explicit; resizing rehashes all entries.
  • get returns undefined when absent, so use has to distinguish that from a stored undefined value.
  • Complexity: Average O(1) for lookup, insertion, and deletion with a well-distributed hash; worst case O(n). Space is O(n + capacity).
Product & growthMediumTencentProduct ManagerGroup interview

13. How can you keep a product alive and popular?

Model answer

Clarify & scope

I’d define “alive and popular” as sustained user value and retention, not a temporary spike in downloads or traffic. I’d first clarify the product’s audience, business model, lifecycle, and strategic role. A social product, a game, and a utility app need different engagement loops, but all need a compelling reason for users to return.

User segments & pain points

I’d choose a core segment whose repeated use creates value for others—for example, players who regularly invite friends, or creators whose content gives viewers a reason to return. I’d investigate what currently brings them back, where they experience friction, and what makes them leave. I’d also check whether new users can reach that value quickly, rather than optimizing only for existing power users.

Goals & success metrics

My North Star would measure recurring value delivered, such as weekly active users who complete a meaningful core action. I’d pair it with cohort retention, successful core-action rate, and user satisfaction. Guardrails would include complaints, churn, content or interaction quality, latency, and monetization pressure. More time spent is not automatically better if the experience becomes frustrating or unhealthy.

Solutions

I’d explore three levers: improve the core experience, create healthy reasons to return, and strengthen the network or content loop. For example, a game could reduce matchmaking friction, offer a meaningful weekly challenge, and make playing with friends easier. A content product might improve relevance and give creators better tools. I’d avoid adding features simply to look active; each one should solve a demonstrated user problem.

Recommendation: Fix the biggest break in the core value loop first, then test one retention or discovery improvement with the most important segment.

Prioritization & trade-offs

I’d rank opportunities by reach, expected retention impact, confidence, and effort. I’d favor a small, reversible experiment over a large feature when evidence is uncertain. Personalization can improve relevance, for example, but should be balanced against privacy, filter bubbles, and perceived control.

MVP, measurement & rollout

I’d define the hypothesis and success threshold before launch, test with a representative cohort, and compare against a control group. I’d monitor both short-term activation and longer-term cohort retention, with guardrails and rollback criteria. If the result holds across segments, I’d expand gradually; otherwise, I’d use the qualitative feedback and funnel data to revise the problem rather than adding more features.

System designMediumTencentBackend Engineer

14. Design a HashMap that supports serialization and deserialization.

Model answer

1. Requirements & scale

I would design a reusable in-memory HashMap with a versioned snapshot format, plus an optional service path for storing and loading snapshots. The serialized form stores entries—not internal buckets—so it remains valid when the implementation changes its capacity or collision strategy.

  • Functional: put, get, delete, iteration, serialize, and deserialize; preserve supported key/value types and distinguish missing keys from null values.
  • Non-functional: expected O(1) map operations, bounded deserialization memory, cross-version compatibility, deterministic output when requested, and safe handling of malformed or untrusted input.
  • Consistency: a snapshot represents one logical point in time. Deserialization either returns a complete map or fails without exposing partial state.

For a reference managed deployment, assume 1 million maps, 100,000 entries per map on average, and 64 bytes per serialized entry: about 6.4 GB per average map, so large maps should be streamed and capped. If 10,000 snapshots are written per day at 10 MB each, storage ingress is about 100 GB/day. The core library has no request QPS requirement; a managed snapshot API can be sized independently.

2. High-level architecture

The map implementation is a client-side library. The diagram shows the optional managed snapshot path; ordinary map operations do not traverse the service tiers.

flowchart TD
  subgraph Client
    A[Application] --> B[HashMap SDK]
  end
  subgraph EdgeCDN["Edge / CDN"]
    C[Snapshot Download Cache]
  end
  subgraph LoadBalancer["Load Balancer"]
    D[Snapshot API LB]
  end
  subgraph APIServices["API / Services"]
    E[Snapshot API]
    F[Format Validator]
  end
  subgraph Cache
    G[Metadata Cache]
  end
  subgraph Datastores
    H[Object Storage]
    I[Snapshot Metadata SQL]
  end
  subgraph MessageQueue["Message Queue"]
    J[Snapshot Events]
  end
  subgraph Workers
    K[Migration and Integrity Worker]
  end
  B -->|serialize map| E
  C -->|download snapshot| B
  E -->|upload or fetch bytes| H
  E -->|read or write metadata| G
  G --> I
  E -->|publish snapshot event| J
  J -->|validate or migrate| K
  K -->|update status| I
  D -->|route API calls| E
Diagram

3. API design

  • Library: map.set(key, value), map.get(key), map.delete(key), map.entries().
  • Library: serialize({ canonical: false }) -> bytes and HashMap.deserialize(bytes, registry, limits) -> map.
  • Managed service: PUT /v1/maps/{mapId}/snapshots creates a snapshot; GET /v1/maps/{mapId}/snapshots/{snapshotId} retrieves it; GET /v1/maps/{mapId}/snapshots/latest resolves the latest committed snapshot.
  • Snapshot writes accept an idempotency key and return a content hash and format version.

4. Data model & storage

Internally, use a power-of-two bucket array with separate chaining or open addressing, a load factor near 0.75, and resize by rehashing. Equality and hashing must be consistent: equal keys must have equal hashes. For custom key types, require registered codecs and stable equality semantics. Do not serialize bucket indexes, capacities, object pointers, or process-specific hash codes.

The binary snapshot contains a magic value, format version, flags, entry count, then length-delimited key/value records with explicit type tags. A footer can carry a checksum. A decoder can skip unknown optional fields but must reject unknown required types. For large snapshots, stream records rather than allocating the entire payload. In managed storage, keep bytes in object storage and map ID, snapshot ID, version, size, checksum, and status in a SQL metadata table partitioned by map ID.

5. Deep dive

The crucial choice is defining a stable wire format independent of the map's in-memory representation. Primitive codecs should have specified byte order and numeric representation. Strings should use UTF-8 with explicit lengths; null needs its own tag. Object codecs must be explicitly registered—never instantiate arbitrary classes based on a class name in untrusted bytes.

sequenceDiagram
  participant App
  participant Map as HashMap SDK
  participant Codec
  participant Store as Snapshot Store
  App->>Map: request snapshot
  Map->>Map: capture consistent entries
  Map->>Codec: encode header and records
  Codec->>Store: write bytes and checksum
  App->>Store: load snapshot
  Store-->>Codec: bytes
  Codec->>Codec: validate limits, version, checksum
  Codec->>Map: build temporary map
  Map-->>App: publish complete map or error
Diagram

For concurrent mutation, either hold a read lock during encoding or use a versioned snapshot/copy-on-write strategy; document the latency and memory trade-off. Deserialization validates the magic, version, record count, lengths, duplicate-key policy, and checksum before publishing the temporary map. Enforce maximum bytes, entries, nesting depth, and string length to prevent memory-exhaustion attacks. Use randomized hashing or collision limits when loading attacker-controlled keys.

Canonical mode can sort entries by their encoded key bytes, but it is only valid when key encoding is canonical and unambiguous. Otherwise, promise semantic equivalence, not identical bytes across runs.

6. Scale, bottlenecks & trade-offs

The local map scales by resizing its bucket array; serialization is O(n) time and O(n) output space, or O(buffer size) additional memory with streaming. Decode is O(n) expected time and may degrade with pathological collisions. A checksum detects accidental corruption; authenticated encryption or a MAC is needed if snapshots must resist tampering.

In the managed path, use immutable, content-addressed snapshot objects and replicate them across availability zones. SQL metadata provides transactional publication: write the object first, then mark the snapshot committed; garbage-collect orphaned objects after failures. Reads can be served through a CDN because committed snapshots are immutable. This favors availability for reads while retaining strong consistency for the latest-snapshot pointer. Schema migration belongs in versioned workers, and old readers should fail explicitly rather than silently misinterpret unsupported required types.

System designHardTencentBackend EngineerEighth Round

15. Design a recommendation system.

Model answer

1. Requirements & scale

I would design a recommendation platform for Tencent surfaces such as video, news, music, games, or WeChat content. The objective is to rank relevant items for each user while respecting eligibility, freshness, privacy, and product constraints.

  • Functional: collect impression and action events; build user/item features; retrieve candidates; rank and filter them; support feedback, experimentation, and cold-start items.
  • Non-functional: p99 feed latency below 150 ms, high availability, rapid reaction to new behavior, explainable offline evaluation, and safe handling of sensitive data.
  • Quality: optimize long-term user value, not just clicks; use guardrails for hides, reports, low-quality sessions, and creator diversity.

Assume 50 million DAU and 20 recommendation impressions per user per day: 1 billion impressions/day, or about 11,600/s average. At a 5x peak, serving is about 58,000 requests/s. If each impression/action event averages 1 KB, that is roughly 1 TB/day raw; compression and columnar storage reduce the retained footprint. With 10 million active items, a 500-candidate request at 2 KB/candidate transfers about 1 MB internally before ranking, so candidate count and feature locality matter.

2. High-level architecture

flowchart TD
  subgraph Client
    A[Feed Client] --> B[Recommendation SDK]
  end
  subgraph EdgeCDN["Edge / CDN"]
    C[API Gateway and CDN]
  end
  subgraph LoadBalancer["Load Balancer"]
    D[Regional Load Balancer]
  end
  subgraph APIServices["API / Services"]
    E[Recommendation Orchestrator]
    F[Candidate Recall]
    G[Online Ranker]
    H[Policy and Eligibility]
  end
  subgraph Cache
    I[User Feature Cache]
    J[Item Feature Cache]
  end
  subgraph Datastores
    K[Feature Store]
    L[User and Item Indexes]
    M[Event Lake]
    N[Model Registry]
  end
  subgraph MessageQueue["Message Queue"]
    O[Behavior Event Stream]
  end
  subgraph Workers
    P[Stream Feature Workers]
    Q[Training and Evaluation]
    R[Index Builder]
  end
  B -->|feed request| C
  C -->|authorized request| D
  D --> E
  E -->|fetch candidates| F
  F -->|vector, graph, hot items| L
  E -->|user features| I
  I --> K
  F -->|item features| J
  J --> K
  F -->|candidate set| G
  G -->|ranked list| H
  H -->|eligible results| E
  B -->|impressions and actions| O
  O -->|events| P
  P -->|live feature updates| K
  O -->|history| M
  M -->|training data| Q
  Q -->|approved model| N
  Q -->|embedding and index updates| R
  R -->|serving indexes| L
Diagram

3. API design

  • POST /v1/recommendations: accepts user/session context, surface, page token, and request ID; returns ranked items, reason codes, and an impression token.
  • POST /v1/events: records impression, click, watch, like, hide, report, or conversion events with event ID and timestamp.
  • GET /v1/items/{itemId}: returns display metadata after eligibility checks.
  • Internal interfaces: Recall(userContext, surface, k) and Rank(userContext, candidates, modelVersion).

Use idempotent event IDs and a request ID for tracing and experiment assignment.

4. Data model & storage

  • Event lake: append-only, partition by event date and surface; include user pseudonymous ID, item ID, event type, context, and experiment assignment. Keep a clearly defined consent and retention policy.
  • Online feature store: key by user ID or item ID; serve compact, versioned features with TTLs. Use a low-latency key-value store and local caches for hot keys.
  • Candidate indexes: vector index for embedding similarity, inverted indexes for topics/tags, and graph or co-occurrence tables for collaborative recall. Partition by region and shard by item or user according to the retrieval path.
  • Model registry: immutable model artifacts, feature schema, training window, evaluation results, and rollout status.

5. Deep dive

Recommendation quality depends on a multi-stage funnel: retrieve broadly, rank accurately, then enforce policy. Retrieval might union user-item collaborative filtering, embedding nearest neighbors, graph neighbors, followed topics, and a freshness pool. Deduplicate, remove already-seen or unavailable items, and cap each source so one source cannot dominate. A practical target is 500–1,000 candidates within roughly 30 ms.

The ranker scores candidates using user, item, and context features. A multi-task model can predict click, watch duration, completion, and negative feedback. Convert calibrated predictions into a product objective, for example score = w1 P(watch) expected_watch_seconds + w2 P(meaningful_action) - w3 P(hide_or_report), with weights selected by product goals and validated offline. Apply freshness and diversity constraints after scoring; never let a model override safety, legal, age, or user-block rules. Return perhaps 20–50 items and log the exact model, feature, and experiment versions used.

sequenceDiagram
  participant C as Client
  participant O as Orchestrator
  participant R as Recall
  participant F as Feature Store
  participant M as Ranker
  participant P as Policy
  C->>O: feed request and context
  O->>F: user and session features
  O->>R: retrieve candidates
  R-->>O: deduplicated candidate IDs
  O->>F: batch item features
  O->>M: score candidates
  M-->>O: scores and predicted outcomes
  O->>P: apply eligibility and diversity
  P-->>C: ranked items and impression token
  C->>O: impression and action events
Diagram

Cold-start users receive contextual, popular, and session-based recommendations, then personalization increases as consented behavior accumulates. New items get metadata/content embeddings and a bounded exploration quota; monitor quality to prevent low-quality items exploiting exploration.

6. Scale, bottlenecks & trade-offs

Run stateless serving services across regions with autoscaling and circuit breakers. Cache stable item features and short-lived user features, but invalidate or version features carefully so recent hides and blocks take effect quickly. Batch feature reads and candidate scoring; set strict per-stage timeouts. If a recall source or feature store is slow, return a smaller result from healthy sources rather than fail the feed. Keep a safe, freshness-aware fallback list.

Use streaming updates for fast-changing counters and interests, and offline batch training for heavier joins and model fitting. The stream path improves responsiveness but can be duplicated or reordered, so event processing must be idempotent and tolerate late events. Serve a stable model version per request; canary new models and roll back using online guardrails. Evaluate with randomized experiments, because offline AUC or NDCG does not prove user benefit. Track latency, availability, coverage, watch quality, hide/report rates, repetition, creator concentration, and long-term retention. Treat recommendation events and user profiles as sensitive: minimize fields, enforce access controls and retention, and honor opt-outs across caches, training data, and serving.

TechnicalEasyTencentSoftware Engineer

16. What are the fundamentals of Java?

Model answer

  1. Java platform: Java source is compiled to bytecode, which runs on the Java Virtual Machine (JVM). The JDK provides development tools such as the compiler; JVM implementations execute bytecode on different operating systems. This enables portability, while JIT compilation can optimize frequently executed code at runtime.
  2. Types and memory: Java is statically typed. Primitive types such as int and double hold values directly, while reference types refer to objects. Objects are generally allocated on the heap; method calls and local variables use thread-specific stacks. Garbage collection reclaims unreachable objects, but developers still need to manage resource lifecycles—for example, closing files with try-with-resources.
  3. Object-oriented design: The core concepts are encapsulation, inheritance, polymorphism, and abstraction. Prefer clear interfaces and composition when they reduce coupling; use inheritance when a true “is-a” relationship exists. Overriding enables runtime polymorphism, while overloading selects methods at compile time.
  4. Exceptions and APIs: Checked exceptions must be declared or handled; unchecked exceptions derive from RuntimeException. Handle errors at the layer that can act on them, preserve useful context, and avoid swallowing exceptions. The standard library provides common APIs for collections, I/O, networking, dates, and concurrency.
  5. Collections and generics: Use interfaces such as List, Set, and Map so implementations can change independently. Generics provide compile-time type safety, such as List<String>. Choose a collection based on access patterns and complexity: for example, HashMap offers expected constant-time key lookup, while TreeMap maintains sorted keys with logarithmic operations.
  6. Concurrency: Java supports threads, executors, synchronization, and higher-level utilities such as concurrent collections. Shared mutable state needs safe coordination; otherwise, races and visibility bugs can occur. Prefer immutable data and executor-based task management where appropriate.
  7. Practical engineering: Strong Java code uses meaningful types, small cohesive methods, tests, and profiling. Know the behavior and costs of the APIs you choose, and measure performance rather than assuming a particular implementation is faster.
TechnicalEasyTencentFrontend EngineerFirst Round

17. What do the HTTP response-code ranges 1xx, 2xx, 3xx, 4xx, and 5xx represent, and what do status codes 501 and 502 mean?

Model answer

HTTP status codes are grouped by their first digit:

  • 1xx — Informational: The request was received and processing is continuing. For example, 100 Continue lets a client proceed with sending a request body.
  • 2xx — Success: The request was successfully received, understood, and handled. Common examples are 200 OK, 201 Created, and 204 No Content.
  • 3xx — Redirection: The client needs to take further action, often by using another URL. Examples include 301 Moved Permanently and 302 Found.
  • 4xx — Client error: The request cannot be completed because of something attributable to the client, such as invalid input, missing credentials, or a nonexistent resource. Examples are 400, 401, 403, and 404.
  • 5xx — Server error: The server failed to fulfill an otherwise valid request, often due to an internal failure or an unavailable dependency. Examples include 500, 502, and 503.

Specifically:

  • 501 Not Implemented: The server does not support the functionality required to fulfill the request. It is commonly used when the server does not recognize or implement a request method or capability.
  • 502 Bad Gateway: A server acting as a gateway or proxy received an invalid response from an upstream server. For example, a frontend-facing API gateway might return 502 if a service it called responded incorrectly or the connection failed.

The key distinction is that 501 describes an unsupported server capability, while 502 describes a failure in communication with an upstream server.

TechnicalEasyTencentBackend EngineerSecond Round

18. How do TCP and UDP differ?

Model answer

TCP and UDP are transport-layer protocols, but they make different trade-offs.

AspectTCPUDP
ConnectionConnection-oriented; establishes a connection before sending dataConnectionless; sends independent datagrams
DeliveryRetransmits lost data and delivers bytes in orderNo built-in delivery, ordering, or duplicate guarantees
ControlFlow control and congestion controlNo built-in flow or congestion control
Data modelOrdered byte stream; message boundaries are not preservedDatagram-oriented; each packet is a separate message
Overhead and latencyMore protocol state and coordinationLower overhead; can avoid connection setup
Typical usesHTTP/HTTPS, databases, file transferDNS, real-time media, games, custom protocols

A TCP connection typically performs a handshake, then exchanges sequenced data and acknowledgments. UDP sends a datagram without that connection setup; an application can add its own reliability or congestion-control logic if needed.

flowchart LR
    A[Application] --> B[TCP or UDP]
    B --> C[IP network]
    C --> D[Remote transport]
    D --> E[Remote application]
    B -. "TCP: ordered, reliable byte stream" .-> D
    B -. "UDP: independent datagrams" .-> D
Diagram

Neither choice is universally faster: TCP is often the right default for correctness, while UDP is useful when the application needs message-oriented delivery or tighter control over latency and recovery.

TechnicalEasyTencentBackend Engineer

19. Explain polymorphism, including whether constructors and destructors can be virtual.

Model answer

Polymorphism lets code use one interface for objects of different concrete types. In C++, the key distinction is static polymorphism (chosen at compile time, such as overloads and templates) versus dynamic polymorphism (chosen at runtime through virtual functions).

struct Handler {
    virtual void handle() { /* default behavior */ }
    virtual ~Handler() = default;
};

struct LoginHandler : Handler {
    void handle() override { /* login behavior */ }
};

Handler* h = new LoginHandler;
h->handle();  // Calls LoginHandler::handle()
delete h;      // Safely calls derived, then base destructor
  • A constructor cannot be virtual: the object’s dynamic type is not established until construction completes. A base constructor can call a virtual function, but dispatch is limited to the class currently being constructed; it will not call an override in a not-yet-constructed derived class. Use a factory function when runtime-dependent construction is needed.
  • A destructor can and often should be virtual. If an object may be deleted through a base-class pointer, the base destructor must be virtual; otherwise, behavior is undefined and the derived destructor may not run. A base class not intended for polymorphic deletion can instead use a protected non-virtual destructor.
TechnicalMediumTencentFrontend EngineerFirst Round

20. How can PHP read a very large file, such as one containing a large array, when PHP has limits on how much it can handle at once?

Model answer

The key is to avoid constructing the entire file—or a huge PHP array—in memory. PHP's memory_limit is a guardrail, not a streaming mechanism.

  1. Choose a streamable format. For data you control, prefer newline-delimited JSON (JSONL), CSV, or another record-per-line format. A single JSON document containing one enormous array is harder to process incrementally.
  2. Read and process records incrementally. SplFileObject or fopen with fgets lets PHP read one line at a time. Decode each JSONL record individually with json_decode, process it, then release references. For CSV, use fgetcsv.
  3. Batch downstream work. Accumulate a bounded batch—for example, 1,000 rows—then write it to the database and clear it. This avoids replacing one large in-memory array with another.
  4. For an existing giant JSON array, use a streaming parser. A library such as JsonMachine can yield elements without decoding the whole document. json_decode(file_get_contents(...)) materializes the whole file and can exceed the limit.
  5. Treat a PHP file that returns a giant array as a format problem. Including or requiring it executes the file and constructs the array in memory. Convert it to a streamable format or import it in bounded chunks; raising memory_limit is only a temporary option when measured memory use safely fits the host.
flowchart TD
    A[Large input file] --> B{Record-oriented format?}
    B -->|Yes| C[Read one record at a time]
    B -->|No| D[Use streaming parser or convert format]
    C --> E[Validate and process record]
    D --> E
    E --> F[Add to bounded batch]
    F --> G{Batch full?}
    G -->|Yes| H[Write batch and clear memory]
    H --> F
    G -->|No| I{More records?}
    I -->|Yes| C
    I -->|No| J[Write final batch]
Diagram

For example, a JSONL reader can keep memory proportional to the largest record rather than the entire file:

$handle = fopen($path, 'rb');
if ($handle === false) {
    throw new RuntimeException('Could not open input file');
}

$batch = [];
$batchSize = 1000;

try {
    while (($line = fgets($handle)) !== false) {
        $record = json_decode($line, true, 512, JSON_THROW_ON_ERROR);
        $batch[] = $record;

        if (count($batch) >= $batchSize) {
            saveBatch($batch); // Application-specific bounded database write.
            $batch = [];
        }
    }

    if (!feof($handle)) {
        throw new RuntimeException('Error while reading input file');
    }

    if ($batch !== []) {
        saveBatch($batch);
    }
} finally {
    fclose($handle);
}

A generator can make this style of processing easier to compose, but it does not help if the code first loads the entire file or builds the entire array. Monitor peak memory and batch size, and handle malformed records explicitly—either fail fast or send them to a quarantine file with line numbers.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions