Skip to content

Cache the expanded Avro schema and inline tags per schema in AvroSerializer and AvroDeserializer - #2457

Open
Alejandro (alexon1234) wants to merge 1 commit into
confluentinc:masterfrom
alexon1234:avro-cache-expanded-schema
Open

Alejandro (alexon1234) wants to merge 1 commit into
confluentinc:masterfrom
alexon1234:avro-cache-expanded-schema

Conversation

@alexon1234

@alexon1234 Alejandro (alexon1234) commented Nov 25, 2026 •

Copy link
Copy Markdown

What

Since 2.14.2 (#2255), AvroDeserializer.__call__ runs fastavro.expand_schema(reader_schema) on every message. It runs whether or not the subject has rules, and get_inline_tags(reader_schema) walks the whole schema on every message too. AvroSerializer does the same with use.latest.version. Both results depend only on the schema, so this work is repeated on every message.

With the 61-field schema in the reproducer below, AvroDeserializer takes about 2.4 times as long per message as it does without these per-message calls. The cost grows with schema size. git bisect between v2.14.0 and v2.14.2 points to 3fd7408 (#2255).

This PR:

  • caches expand_schema(...) and get_inline_tags(...) per Schema in AvroSerializer and AvroDeserializer, next to the existing parsed-schema cache;
  • computes them in the deserializer only inside the ctx is not None and subject is not None block, which is the only place they are used.

Behavior does not change. _get_parsed_schema returns the same parsed schema for a given Schema, transform does not modify the schema it reads, and RuleContext only reads the inline tags.

Reproducer

MockSchemaRegistryClient, one schema, the same message deserialized 50,001 times:

import io
import json
import struct
import time

import fastavro
import fastavro.schema

import confluent_kafka.schema_registry._sync.avro as avro_module
from confluent_kafka.schema_registry import Schema
from confluent_kafka.schema_registry._sync.mock_schema_registry_client import MockSchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer
from confluent_kafka.serialization import MessageField, SerializationContext

MESSAGES = 50_000

fields = [{"name": f"f{i}", "type": ["null", "string"] if i % 2 else "long"} for i in range(50)]
nested_fields = [{"name": f"n{i}", "type": "string"} for i in range(10)]
fields.append({"name": "nested", "type": {"type": "record", "name": "Nested", "fields": nested_fields}})
schema = {"type": "record", "name": "Wide", "fields": fields}
record = {f"f{i}": (f"v{i}" if i % 2 else i) for i in range(50)}
record["nested"] = {f"n{i}": "x" for i in range(10)}

registry = MockSchemaRegistryClient({"url": "mock://"})
schema_id = registry.register_schema("topic-value", Schema(json.dumps(schema), "AVRO"))
buffer = io.BytesIO()
buffer.write(struct.pack(">bI", 0, schema_id))
fastavro.schemaless_writer(buffer, fastavro.parse_schema(schema), record)
message = buffer.getvalue()

expand_schema_calls = 0
if hasattr(avro_module, "expand_schema"):
    def counting_expand_schema(schema):
        global expand_schema_calls
        expand_schema_calls += 1
        return fastavro.schema.expand_schema(schema)

    avro_module.expand_schema = counting_expand_schema

deserializer = AvroDeserializer(registry)
ctx = SerializationContext("topic", MessageField.VALUE)
assert deserializer(message, ctx) == record

start = time.perf_counter()
for _ in range(MESSAGES):
    deserializer(message, ctx)
elapsed = time.perf_counter() - start
print(f"{elapsed / MESSAGES * 1e6:.1f} us/message, "
      f"{expand_schema_calls} expand_schema calls for {MESSAGES + 1} messages")

Python 3.13, fastavro 1.13.1, x86_64 Linux:

µs/message expand_schema calls
confluent-kafka 2.16.1 50.1 50,001
This PR 20.8 1

Checklist

  • Contains customer facing changes? Including API/behavior changes
    • No API or behavior change. Avro serialization and deserialization use less CPU.
  • Did you add sufficient unit test and/or integration test coverage for this PR?
    • test_avro_deserializer_expands_reader_schema_once and test_avro_serializer_expands_latest_schema_once (async, plus the sync versions generated by tools/unasync.py). Both fail on master and pass with this change.

References

Test & Review

  • pytest on these tests: tests/schema_registry/{_sync,_async}/test_avro.py, test_avro_serdes.py and test_avro_serdes_rules.py, and tests/schema_registry/_sync/test_cel_avro_message_transform.py, test_dlq_serdes.py and test_validation_serdes.py. Result: 341 passed (337 existing, 4 new).
  • To check the cached data against repeated use, the sync Avro tests were also run with every AvroDeserializer call made twice, and both results must be equal. Result: 192 passed, the same as on master.
  • tools/unasync.py --check, flake8, black, isort, and mypy on the changed modules all pass.

Open questions / Follow-ups

  • The serializer path that runs only when inline validation rules are enabled and no latest schema is used still calls expand_schema(self._parsed_schema) on every message. It is not cached here because its parsed schema does not come from _get_parsed_schema.

AvroSerializer and AvroDeserializer ran fastavro.expand_schema and get_inline_tags on every message (confluentinc#2255). Cache both per Schema, and compute them in the deserializer only when it executes rules.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@confluent-cla-assistant

Copy link
Copy Markdown

❌ The following commits have a committer email that isn't linked to a Github account, so their CLA status can't be verified. Please link the email to your Github account (or correct your git config) and push again:
❌ a956501
Please push an empty commit if you would like to re-run the checks to verify CLA status for all contributors.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

No active review issues were identified for the Avro schema-caching changes.

No open issues 🎉

What changed in this PR

This PR addresses the Avro performance regression reported in #2458 by caching schema-derived data in the synchronous and asynchronous serializers and deserializers.

Changes:

  • Cache expanded schemas and inline tags per Schema, avoiding repeated work for deserialization and serialization with use.latest.version.
  • Move deserializer cache access inside the block requiring a serialization context and subject.
  • Add regression tests verifying schema expansion occurs once across repeated messages, and document the fix.
File Description
tests/​schema_registry/​_sync/​test_avro_serdes.py Adds synchronous regression tests for schema-expansion caching.
tests/​schema_registry/​_async/​test_avro_serdes.py Adds asynchronous regression tests for schema-expansion caching.
src/​confluent_kafka/​schema_registry/​_sync/​avro.py Adds schema-derived caches and conditional deserializer preprocessing.
src/​confluent_kafka/​schema_registry/​_async/​avro.py Implements matching caching behavior for asynchronous Avro operations.
CHANGELOG.md Documents the Avro performance fix.

Review effort: Balanced

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AvroSerializer and AvroDeserializer run expand_schema and get_inline_tags on every message (slower since 2.14.2)

2 participants