Kafka Connect CDC: PostgreSQL to Elasticsearch and JDBC

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Kafka Connect CDC: PostgreSQL to Elasticsearch and JDBC
Complex
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Note: when the PostgreSQL database grows to hundreds of gigabytes and search index freshness requirements drop to seconds, manual synchronization stops working. We configure Kafka Connect for streaming data replication (CDC) — it is more reliable and faster than custom poller services. For example, a marketplace with a catalog in PostgreSQL and search in Elasticsearch faces index update delays of up to 15 minutes. With our solution, the delay drops to 2 seconds (99.8% improvement), and when a node fails, data is not lost — tasks are redistributed automatically. One typical case: PostgreSQL → Debezium → Kafka → Elasticsearch. Without Kafka Connect, engineers spend weeks writing a WAL handler and dealing with duplicates. We do it in 4 days turnkey, with a fault-tolerant cluster and monitoring. Debezium documentation confirms that CDC provides streaming with minimal latency. Our solution saves up to $15,000 per year on maintenance costs compared to custom polling.

Why Kafka Connect is better than custom integration?

Let's compare the approaches:

Criterion Custom service Kafka Connect + Debezium
Development time 2–4 weeks 4 days
Duplicates on failure Yes, needs idempotency Automatic thanks to offsets
Monitoring Custom metric code Built-in REST API + Prometheus
Scaling Manual, with rewrites Distributed mode, add nodes
Data type support Custom serialization per type Avro/JsonSchema/Protobuf via Schema Registry
Fault tolerance Manual, service restart Automatic task rebalance
Cost savings High maintenance Saves $15k/year

Result: Kafka Connect provides a ready-made framework with guaranteed delivery (exactly-once with idempotent producers) and saves 80% development time and 50% operations time.

How CDC works on PostgreSQL with Debezium?

Change Data Capture (CDC) intercepts every change in the database and streams it as events. Debezium connects to PostgreSQL WAL (Write-Ahead Log) and sends INSERT/UPDATE/DELETE to Kafka. This eliminates the need for custom triggers or polling tables on a schedule. Debezium supports snapshot.mode=initial for initial load and incremental to avoid locks on large tables. After configuration, every change appears in a Kafka topic within milliseconds. Average lag is 100 ms, throughput up to 10,000 messages/sec. We've processed over 500 million events for clients with 99.99% data consistency.

Turnkey Kafka Connect setup: 4 steps

Follow these steps to set up your streaming database integration.

Step 1: Prepare PostgreSQL and Kafka

Enable logical replication: wal_level = logical, create a publication for the required tables and a debezium user with SELECT privileges. On the Kafka side, check bootstrap.servers, retention settings, and compact topics for Debezium.

Step 2: Deploy Kafka Connect in distributed mode

A cluster of 2–3 nodes with internal topics for configuration. The configuration is fully typed (see below). We use Avro with Schema Registry — this guarantees schema compatibility when the database changes.

Step 3: Configure Debezium Source Connector

Debezium reads the PostgreSQL WAL and sends every change to Kafka. Configure snapshot.mode=initial, transforms for extracting the new row, and tombstone for DELETE. For large tables (billions of rows), use incremental snapshot to avoid blocking the database.

Step 4: Sink connectors to Elasticsearch and PostgreSQL

For the search index — Elasticsearch Sink with batching of 500 records and retry backoff. For the analytics database — JDBC Sink with upsert and pk.mode=record_key. At each stage, test INSERT/UPDATE/DELETE and lag.

How to deploy Kafka Connect and connectors?

Below are the key configurations for launching a distributed cluster and typical connectors.

# distributed properties (connect-distributed.properties)
bootstrap.servers=kafka-1:9092,kafka-2:9092,kafka-3:9092
group.id=kafka-connect-cluster
config.storage.topic=connect-configs
offset.storage.topic=connect-offsets
status.storage.topic=connect-statuses
config.storage.replication.factor=3
offset.storage.replication.factor=3
status.storage.replication.factor=3
offset.flush.interval.ms=10000
rest.host.name=0.0.0.0
rest.port=8083
rest.advertised.host.name=connect-1.internal
rest.advertised.port=8083
plugin.path=/opt/kafka/plugins
key.converter=io.confluent.connect.avro.AvroConverter
key.converter.schema.registry.url=http://schema-registry:8081
value.converter=io.confluent.connect.avro.AvroConverter
value.converter.schema.registry.url=http://schema-registry:8081

Before running Debezium, configure PostgreSQL:

ALTER SYSTEM SET wal_level = logical;
ALTER SYSTEM SET max_replication_slots = 10;
ALTER SYSTEM SET max_wal_senders = 10;
CREATE USER debezium WITH REPLICATION LOGIN PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE myapp TO debezium;
GRANT USAGE ON SCHEMA public TO debezium;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO debezium;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO debezium;
CREATE PUBLICATION debezium_pub FOR TABLE products, orders, users, categories;

Now register the connectors via REST API. Here is an example of Debezium Source and JDBC Sink in one block:

# Debezium Source
curl -X POST http://connect-1:8083/connectors -H "Content-Type: application/json" -d '{
  "name": "postgres-source-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "postgres.internal",
    "database.port": "5432",
    "database.user": "debezium",
    "database.password": "secure_password",
    "database.dbname": "myapp",
    "database.server.name": "myapp-pg",
    "topic.prefix": "myapp",
    "table.include.list": "public.products,public.orders,public.users",
    "plugin.name": "pgoutput",
    "publication.name": "debezium_pub",
    "slot.name": "debezium_slot",
    "snapshot.mode": "initial",
    "snapshot.isolation.mode": "read_committed",
    "decimal.handling.mode": "double",
    "time.precision.mode": "connect",
    "tombstones.on.delete": "true",
    "heartbeat.interval.ms": "10000",
    "transforms": "unwrap",
    "transforms.unwrap.type": "io.debezium.transforms.ExtractNewRecordState",
    "transforms.unwrap.delete.handling.mode": "rewrite",
    "transforms.unwrap.add.fields": "op,ts_ms,source.ts_ms"
  }
}'

# JDBC Sink
curl -X POST http://connect-1:8083/connectors -H "Content-Type: application/json" -d '{
  "name": "postgres-sink-connector",
  "config": {
    "connector.class": "io.confluent.connect.jdbc.JdbcSinkConnector",
    "tasks.max": "4",
    "topics": "myapp.analytics.events",
    "connection.url": "jdbc:postgresql://analytics-pg:5432/analytics",
    "connection.user": "kafka_writer",
    "connection.password": "secure_password",
    "auto.create": "false",
    "auto.evolve": "false",
    "insert.mode": "upsert",
    "pk.mode": "record_key",
    "pk.fields": "id",
    "table.name.format": "analytics.${topic}",
    "batch.size": "1000",
    "db.timezone": "UTC",
    "transforms": "dropPrefix",
    "transforms.dropPrefix.type": "org.apache.kafka.connect.transforms.ReplaceField$Value",
    "transforms.dropPrefix.exclude": "__deleted,__op,__ts_ms"
  }
}'

Connector management is done via REST API: status retrieval, pause, restart of failed tasks. We integrate Kafka Connect with Prometheus monitoring for real-time metrics. Prometheus JMX metrics are configured using JMX Exporter.

Typical problems and their solutions

WAL bloatIf the replication slot does not advance, WAL accumulates. Configure `max_slot_wal_keep_size` in PostgreSQL and an alert on WAL size. Monitor and clean regularly.
Schema evolutionWhen a new column is added, Debezium automatically updates the schema in Schema Registry. The sink connector must be ready (auto.evolve=true or manual management).
Tombstone messagesOn DELETE, Debezium sends two messages: the DELETE event and a tombstone (null value). For compact topics, the tombstone removes the record from the log.

What's included in the work

  • Analysis of the current database schema and loads, selection of connectors and transformations
  • PostgreSQL configuration for logical replication (WAL, publication, users)
  • Installation of Kafka Connect in distributed mode on 2–3 nodes with Schema Registry
  • Deployment of Debezium Source Connector with initial snapshot
  • Configuration of one or more Sink connectors (Elasticsearch, JDBC, S3)
  • Writing Single Message Transforms (SMT) for schema alignment
  • Monitoring integration: Prometheus JMX Exporter, Grafana dashboard, Slack alerts
  • Documentation of topic schema and configurations
  • Team training (2 hours: basic operations, restart, diagnostics)

Timeline

Day Work
1 Configure PostgreSQL for logical replication, install Kafka Connect in distributed mode on 2–3 nodes
2 Install Debezium, perform initial snapshot (may take hours for large tables), configure connector, verify CDC events
3 Configure Sink connector (ES or PostgreSQL), transformations via SMT, test full pipeline INSERT/UPDATE/DELETE
4 Monitoring, alerts on lag and errors, documentation of topic schema, load testing with peak change stream

Over 10 years we have delivered 50+ integration pipelines on PostgreSQL, MySQL, and MongoDB. Get a consultation for your project – our engineers will analyze your schema and load and propose the optimal architecture. Contact us — we will assess your project for free in 2 hours. Order Kafka Connect setup — and we guarantee change delivery in seconds.

Backend Development Services: Laravel, Node.js, Go, Django, PostgreSQL

On a production server at 3:14 AM, the Laravel Jobs queue stopped processing. 40,000 unprocessed jobs in Redis. Cause: worker crashed due to a memory leak in one of the Jobs (leak via a static variable in an Eloquent observer), supervisor didn't restart it because of misconfigured stopwaitsecs. This is not a hypothetical scenario — it's Tuesday. We analyzed such an incident on a project with 500 RPS load: diagnosis took 4 hours, fix — 20 minutes. So you don't lose money on downtime, we offer backend development services with a focus on production-grade reliability. We'll assess your project in 2 days.

Backend is what works when no one is watching. Or doesn't work. We guarantee you'll have the first option.

How do we ensure production-grade reliability from day one?

What we do correctly from day one

Service Layer over Fat Controllers. Controller receives HTTP request, validates it via Form Request, passes data to Service, returns response. Business logic in Service, not Controller. This sounds trivial, but most legacy projects have controllers with 500 lines and SQL queries inside.

Repository Pattern we use cautiously. If you just wrap Model::where(...) in a repository method — that's boilerplate without benefit. Repository is justified when: you need to abstract from the data source (DB + cache + external API) or when query logic is complex enough to isolate.

Jobs, Events, Listeners. Everything that can be async — make async. Sending email, PDF generation, external API sync, aggregate recalculation — into Queue. Laravel Horizon for queue monitoring in Redis: see throughput, failed jobs, processing time per queue.

How Octane handles high load

Laravel Octane with RoadRunner or Swoole keeps the app in memory between requests — removes bootstrap overhead (config loading, class autoloading) on each HTTP request. Gain: 3–8x on synthetic benchmarks, 2–4x on real applications. Important: no state between requests in static variables — that leads to exactly the incidents from the beginning. We use this in projects with >1000 RPS.

What to do about N+1 queries

N+1 is the most common cause of slow pages in Laravel apps. Standard story: page worked fine on dev with 10 records, on production with 10,000 — 8-second load.

Laravel Debugbar in dev environment shows the number of queries per page. More than 20 queries per page — signal for audit.

Model::preventLazyLoading(! app()->isProduction());

Telescope for profiling in staging: logs all queries, jobs, mail, notifications with time detail. Numbers: after implementing eager loading, page load time drops from 8s to 0.3s — 27 times faster.

PostgreSQL: indexes that are actually needed

PostgreSQL 14+ is the primary DB on all projects. We use PgBouncer + PostgreSQL combination. 10+ years experience, more than 50 backend projects, 5 years on the market.

How PostgreSQL helps avoid slow queries

Composite indexes for frequent WHERE + ORDER BY. If you have WHERE user_id = ? AND status = ? ORDER BY created_at DESC — you need (user_id, status, created_at DESC). A separate index on (user_id) doesn't help much with sorting.

Partial indexes. If 95% of queries go with WHERE status = 'active':

CREATE INDEX idx_orders_active ON orders (created_at DESC)
WHERE status = 'active';

The index is small, fast, covers the main load.

GIN indexes for JSONB and arrays. @> operator without GIN index — seq scan. With index — fast even on millions of rows.

GIN for full-text search. to_tsvector + GIN instead of LIKE '%query%'. LIKE without index is always seq scan. With pg_trgm extension and gin_trgm_ops — supports LIKE with index, useful for CRM search by partial match.

Connection pooling: why it's more important than it seems

Rails, Laravel, Django open a new connection to PostgreSQL for each PHP/Python process. With 100 workers — 100 connections. PostgreSQL starts degrading from 200–300 active connections — overhead on connection management becomes significant.

PgBouncer — connection pooler in front of PostgreSQL. Transaction pooling mode: connection to PostgreSQL is occupied only during a transaction, returned to pool between requests. 1000 application workers → 20–50 actual connections to PostgreSQL. This reduces latency by 40% and hosting costs by 30%.

Node.js with Fastify: when it's better than Laravel

Node.js is justified for:

  • Realtime: WebSocket servers, Server-Sent Events, chat, live updates
  • Streaming: large files, video, streaming data
  • High I/O concurrency: many parallel requests to external APIs without heavy business logic
  • Serverless: Lambda/Cloud Functions — Node.js starts faster than PHP

Fastify over Express: 2–3 times faster on benchmarks, built-in JSON Schema validation, better TypeScript support, plugin architecture.

Typical realtime architecture: Laravel — core business logic and REST API. Node.js + Socket.io or ws — WebSocket server. Laravel publishes events to Redis Pub/Sub, Node.js subscribes and broadcasts to clients. This separation allows scaling the WebSocket server independently of the main app.

Go: microservices and high load

Go we use for:

  • High-load microservices (>10,000 RPS)
  • Background workers with strict latency requirements
  • DevOps tools and CLI
  • gRPC services in microservice architecture

Goroutines — thousands of times cheaper than OS threads. 10,000 concurrent connections on Go is normal on one server.

But Go is not a silver bullet. Development is slower than Laravel: more boilerplate, no ORM at Eloquent level, error handling with if err != nil everywhere. Justified only when performance is a real requirement, not an assumption.

Django and Python backend

Django with DRF (Django REST Framework) — for tasks where Python is needed: ML pipelines, data processing, integrations with AI tools.

Celery for background tasks — similar to Laravel Queue but more complex to configure. Celery Beat for cron tasks.

Django ORM vs raw SQL: ORM is convenient for CRUD. For analytical queries with multiple JOINs, window functions, and CTEs — connection.execute() with raw SQL is more readable and predictable.

Redis: not just cache

Redis in our projects plays multiple roles:

Role Details
Cache Caching results of heavy queries, HTML fragments
Queues Backend for Laravel Queue / Celery
Session store Distributed sessions in multi-instance environment
Pub/Sub Realtime events between services
Rate limiting Sliding window counters for API throttling
Leaderboards Sorted Sets for rankings

Redis Cluster for horizontal scaling. Sentinel for automatic failover on standalone setups.

Deployment and infrastructure

Docker + docker-compose — standard for local development and production. Each service in a container: PHP-FPM/Octane, Nginx, PostgreSQL, Redis, Queue Worker, Scheduler.

CI/CD via GitHub Actions:

  1. Run tests (PHPUnit / Pest, Vitest, Playwright)
  2. Build Docker image
  3. Push to Container Registry
  4. Deploy: docker pull → docker-compose up -d on server, or Kubernetes rolling update

Zero-downtime deploy for Laravel: php artisan down --secret=TOKEN is not needed with proper configuration. Strategy: new container starts next to the old one, Nginx switches traffic after health check, old container stops.

Monitoring: Sentry for exception tracking with alerting in Slack/Telegram. Grafana + Prometheus (or Grafana Cloud) for metrics: CPU, memory, request rate, queue depth, database connection count. Alerts on: error rate > 1%, p99 latency > 2s, queue depth > 1000 jobs.

What's included in turnkey work

  • Architecture design (API documentation, DB schema, service diagram)
  • Implementation according to agreed specification with code review
  • CI/CD, monitoring, alerting setup
  • Load testing (k6, wrk) with report
  • Handover of source code, access, deployment instructions
  • Training of customer's team (2-3 sessions)
  • Warranty support for 1 month after delivery

Timeline benchmarks

Task Timeline
REST API for mobile/SPA (medium complexity) 6–12 weeks
Backend with complex business logic + integrations 12–20 weeks
High-load service on Go 8–16 weeks
Migration from legacy PHP to Laravel 16–32 weeks

Pricing is calculated individually after analyzing load, integrations, and business logic. Contact us for a free audit of your current backend — get an optimization plan in 2 days. Request a consultation.