ByteDance Backend Interview: Java OOM, ThreadPool Tuning, Redis & MQ

ByteDance’s recent salary announcements show higher offers up to 40K, while the company’s rigorous backend interview covers Java heap OOM analysis, JVM tuning, thread‑pool configuration, Redis expiration strategies, MQ usage, network request flow, and algorithm challenges, providing a comprehensive technical deep‑dive for candidates.

JavaGuide
JavaGuide
JavaGuide
ByteDance Backend Interview: Java OOM, ThreadPool Tuning, Redis & MQ

Salary Overview

ByteDance has recently disclosed salary ranges for backend positions in Beijing, with offers ranging from 26K to 40K (SSP) and signing bonuses up to 10W+. Some reports mention offers exceeding 40K, though verification is pending.

Interview Difficulty

The interview difficulty remains high; many questions probe low‑level fundamentals. Pure algorithmic coding is insufficient—candidates must master core computer‑science concepts.

Java Heap OutOfMemoryError

OutOfMemoryError: Java heap space occurs when the JVM cannot allocate a contiguous memory block for a new object, even after garbage collection.

Typical causes:

Memory leak : objects remain referenced, e.g., a static List that grows indefinitely or a ThreadLocal without remove().

Memory bloat : massive object creation in a short period, such as loading millions of rows into a list or reading an entire large file into memory.

Enable automatic heap dump on OOM:

# Generate a heap dump when OOM occurs
-XX:+HeapDumpOnOutOfMemoryError
# Specify dump file path
-XX:HeapDumpPath=<path-to-dump-dir>

Analyze the dump with tools like MAT or JVisualVM. MAT’s “Leak Suspects” report highlights the most suspicious objects; the Dominator Tree view shows which objects dominate memory usage.

Example code that deliberately leaks memory:

import java.util.ArrayList;
import java.util.List;

public class SimpleLeak {
    // static collection lives as long as the JVM
    public static List<byte[]> staticList = new ArrayList<>();

    public void leakMethod() {
        // add a 1 MB byte array each call
        staticList.add(new byte[1024 * 1024]);
    }

    public static void main(String[] args) throws InterruptedException {
        SimpleLeak leak = new SimpleLeak();
        System.out.println("Starting leak simulation...");
        for (int i = 0; i < 200; i++) {
            leak.leakMethod();
            System.out.println("Added " + (i + 1) + " MB to the list.");
            Thread.sleep(200);
        }
        System.out.println("Leak simulation finished. Keeping process alive for Heap Dump.");
        Thread.sleep(Long.MAX_VALUE);
    }
}

Running the program with a small heap (e.g., -Xmx256m) quickly triggers OOM and produces simple_leak.hprof. Importing the dump into MAT shows that SimpleLeak.staticList consumes ~115 MB (≈98.8% of the heap), confirming the leak.

JVM Heap Parameters

Key parameters for controlling heap size: -Xms: initial heap size (e.g., -Xms512m). -Xmx: maximum heap size (e.g., -Xmx1g).

In production it is recommended to set -Xms and -Xmx to the same value to avoid dynamic heap resizing and associated Full GCs.

New‑generation and old‑generation tuning: -Xmn: directly sets young‑gen size (takes precedence over -XX:NewRatio). -XX:NewRatio: ratio of old‑gen to young‑gen (default 2:1). -XX:SurvivorRatio: ratio of Eden to each Survivor space (default 8:1).

ThreadPool Fundamentals

A thread pool manages a pool of worker threads, reducing thread‑creation overhead, improving response latency, and providing better control over concurrency.

Important ThreadPoolExecutor parameters: corePoolSize: maximum concurrent threads before queuing. maximumPoolSize: maximum threads when the queue is full. workQueue: task queue used after core threads are busy. keepAliveTime: idle time after which non‑core threads are terminated. allowCoreThreadTimeOut (available since JDK 1.6): when set to true, core threads also respect keepAliveTime and can be terminated.

Example creating a pool with core size 5, max size 5, and a 10‑second keep‑alive, then enabling core‑thread timeout:

ThreadPoolExecutor executor = new ThreadPoolExecutor(
    5, 5, 10L, TimeUnit.SECONDS,
    new LinkedBlockingQueue<>(15)
);
executor.allowCoreThreadTimeOut(true);
for (int i = 0; i < 10; i++) {
    executor.execute(() -> System.out.println(Thread.currentThread().getName()));
}

Note: keepAliveTime applies only to non‑core threads unless allowCoreThreadTimeOut is enabled; otherwise core threads stay alive indefinitely.

Redis Expiration & HotKey Management

Expiration commands:

EXPIRE key seconds
PEXPIRE key milliseconds
EXPIREAT key timestamp
PEXPIREAT key msTimestamp

String shortcuts: SET key value EX seconds, SET key value PX ms, SETEX key seconds value Redis stores expiration timestamps in an expires dictionary inside the redisDb structure. Lookup is O(1); if a key is found in the dictionary, its timestamp is checked and the key is deleted if expired.

Deletion strategy combines periodic scanning (CPU‑friendly) and lazy deletion (memory‑friendly).

HotKey definition: a key whose access frequency far exceeds others (e.g., 2000 QPS in a 5000 QPS workload). HotKeys can cause CPU, bandwidth, and stability issues.

Mitigation techniques:

Read‑write separation (writes to master, reads from replicas).

Redis Cluster to shard hot data across nodes.

Secondary cache (e.g., Caffeine) to keep hot entries in JVM memory.

Sorted Set (zset) Implementation

Redis zset (Sorted Set) stores elements with a score for ordering. Internally it uses a skip‑list (similar to ConcurrentSkipListMap) combined with a hash table for O(log N) range queries and O(1) lookups.

When the number of elements < 128 and each element < 64 bytes, Redis stores the set in a compact ziplist. The thresholds are controlled by zset-max-ziplist-entries 128 and zset-max-ziplist-value 64. Exceeding either threshold converts the structure to a skip‑list.

Message Queue (MQ) Benefits & Delay Levels

Using a message queue improves system performance via asynchronous processing, smooths traffic spikes, and reduces coupling between services.

RocketMQ 4.x supports 18 predefined delay levels (1 s to 2 h). RocketMQ 5.0 introduces a time‑wheel algorithm for arbitrary timed messages, overcoming the fixed‑level limitation.

Network Request Flow

Enter URL in browser.

DNS resolves domain to IP.

TCP three‑way handshake to the server.

Browser sends HTTP request.

Server processes request and returns HTTP response.

Browser parses HTML, fetches additional resources (CSS, JS, images) as needed.

Connection is closed when idle or by the server.

HTTP vs. HTTPS

Port: HTTP 80, HTTPS 443.

URL scheme: http:// vs. https://.

Security: HTTPS runs over TLS/SSL, encrypting traffic and providing server authentication; HTTP transmits plaintext.

SEO: Search engines prefer HTTPS sites.

Algorithm Reference

LeetCode problem “Longest Substring Without Repeating Characters” (medium) is linked for interview practice.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaJVMRedisNetworkThreadPoolinterviewMessageQueue
JavaGuide
Written by

JavaGuide

Backend tech guide and AI engineering practice covering fundamentals, databases, distributed systems, high concurrency, system design, plus AI agents and large-model engineering.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.