Video in progress

You need to send large payloads (say, a 20 MB PDF or an image) through Kafka. How do you approach it?

Kafka isn't designed for big messages: the default limit is ~1 MB, and large messages slow down broker memory, replication and consumers. I use the claim check pattern: put the file in object storage and send only a reference and metadata to Kafka.

📖 Answer

Raising message.max.bytes, max.request.size, max.partition.fetch.bytes and replica.fetch.max.bytes to 50 MB is technically possible. But the consequences:

  • every large message is loaded fully into memory on the broker, on the replicas and in each consumer;
  • the small messages behind one 20 MB message wait too, so latency spikes;
  • the page cache fills up with big blobs, and the "hot" data of other topics gets pushed out;
  • 7 days of retention × RF 3 is the most expensive way to store blobs.

Claim check:

String key = "invoices/%s/%s.pdf".formatted(LocalDate.now(), invoiceId);
s3.putObject(b -> b.bucket("docs").key(key), RequestBody.fromBytes(pdf));
kafka.send("invoice.generated.v1", invoiceId.toString(),
        new InvoiceGenerated(invoiceId, "s3://docs/" + key, pdf.length, sha256(pdf)));

The consumer takes the reference and downloads the file if it needs to. Many consumers use only the metadata, not the file itself, and for them this is even faster.

Questions to settle:

  • Ordering: write the file first, then the event; otherwise a consumer gets a reference to a file that doesn't exist yet;
  • Lifecycle: when is the file deleted? It has to outlive the retention, otherwise the references are dead during a replay. Use a lifecycle policy;
  • Access: instead of giving consumers full bucket access, you can give a short-lived presigned URL, but it expires before the event's retention does, so I often give the service a role instead;
  • Integrity: send the hash in the event.

The borderline case is 1-5 MB messages. For those I first try compression (zstd) and trimming the payload; often that alone is enough.