apache/kafka · error · java.lang.IllegalArgumentException

Topic pattern to subscribe to cannot be empty

Error message

Topic pattern to subscribe to cannot be empty

What it means

Thrown by subscribeInternal(Pattern, Optional) when the supplied Pattern is non-null but its string form is empty (pattern.toString().isEmpty()). An empty pattern would match no topics (or, depending on regex engine, behave unexpectedly), so the client rejects it before sending a TopicPatternSubscriptionChangeEvent.

Source

Thrown at clients/src/main/java/org/apache/kafka/clients/consumer/internals/AsyncKafkaConsumer.java:2249

                " otherThread(id: " + currentThread.get() + ")"
            );
        refCount.incrementAndGet();
    }

    /**
     * Release the light lock protecting the consumer from multithreaded access.
     */
    private void release() {
        if (refCount.decrementAndGet() == 0)
            currentThread.set(NO_CURRENT_THREAD);
    }

    private void subscribeInternal(Pattern pattern, Optional<ConsumerRebalanceListener> listener) {
        acquireAndEnsureOpen();
        try {
            throwIfGroupIdNotDefined();
            if (pattern == null || pattern.toString().isEmpty())
                throw new IllegalArgumentException("Topic pattern to subscribe to cannot be " + (pattern == null ?
                    "null" : "empty"));
            log.info("Subscribed to pattern: '{}'", pattern);
            applicationEventHandler.addAndGet(new TopicPatternSubscriptionChangeEvent(
                pattern,
                listener,
                defaultApiTimeoutDeadlineMs()
            ));
        } finally {
            release();
        }
    }

    /**
     * Subscribe to the RE2/J pattern. This will generate an event to update the pattern in the
     * subscription state, so it's included in the next heartbeat request sent to the broker.
     * No validation of the pattern is performed by the client (other than null/empty checks).
     */
    private void subscribeToRegex(SubscriptionPattern pattern,

View on GitHub (pinned to c31c9215e1)

Solutions

  1. Validate the source string before compiling: if (patternStr == null || patternStr.isBlank()) throw / default.
  2. Provide a meaningful default regex when configuration is empty.
  3. Add a startup assertion that the resolved pattern is non-blank.

Example fix

// before
String s = props.getProperty("topics.pattern", "");
consumer.subscribe(Pattern.compile(s)); // empty string -> throws

// after
String s = props.getProperty("topics.pattern");
if (s == null || s.isBlank()) {
    throw new IllegalStateException("topics.pattern must be a non-empty regex");
}
consumer.subscribe(Pattern.compile(s.trim()));
Defensive patterns

Strategy: validation

Validate before calling

// Before consumer.subscribe(pattern):
if (pattern == null || pattern.toString().isEmpty())
    throw new IllegalArgumentException("pattern must be non-null and non-empty");
// or filter blank patterns out of any dynamic list before subscribing.

Type guard

static boolean isNonEmptyPattern(Pattern p) {
    return p != null && !p.toString().isEmpty();
}

Try / catch

try {
    consumer.subscribe(pattern);
} catch (IllegalArgumentException e) {
    if (e.getMessage().contains("cannot be empty")) {
        log.warn("Empty pattern; no topics will match, skipping subscribe", e);
    } else throw e;
}

Prevention

When it happens

Trigger: Calling consumer.subscribe(Pattern.compile("")); passing a Pattern built from a configuration property that resolved to an empty string; trimming/normalization that produced an empty regex.

Common situations: Configuration property defaulted to empty string instead of null; YAML/JSON config where the pattern key exists but value is blank; environment variable substituted to empty; UI/admin tooling that submits an empty field.

Related errors


AI-assisted analysis of apache/kafka@c31c9215e1 (2026-08-03). Data as JSON: /data/errors/ead96fa87e2b18ee.json. Report an issue: GitHub.