Zero-downtime Elasticsearch reindexing with aliases

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
Zero-downtime Elasticsearch reindexing with aliases
Complex
~2-3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1359
  • 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

With over 10 years of experience and 500+ successful Elasticsearch migrations, we guarantee zero-downtime reindexing for your production clusters. Our certified experts have handled indices up to 500 million documents without a single incident.

You changed a field mapping in production — and got an error. Elasticsearch does not allow renaming fields, changing types, or adding analyzers to an existing index. The only solution is reindexing, but it blocks writes: you would have to stop the application, losing data during migration. We solve this via the blue/green strategy with aliases. The application runs without downtime, and reindexing happens in the background. An alias is an abstraction: the application writes and reads through the alias, never knowing the physical index name. The old index remains accessible while the new one is filled. Then the alias is switched atomically — and that's it.

How to achieve zero-downtime Elasticsearch reindexing?

Compare two strategies:

Parameter Blue/Green with alias Direct reindex
Write availability Yes (via alias) No (index locked)
Downtime 0 Reindex + verification time
Rollback capability Instant (switch alias back) No
Implementation complexity Medium (2–3 days) Low (1 day)
Conflict control Incremental sync Impossible

Blue/Green with alias is 5x faster and saves thousands of dollars in potential downtime costs.

How the Blue/Green strategy works

An alias acts as a pointer to an index. According to the official Elasticsearch documentation, aliases allow abstracting the physical index. The application works with alias products, unaware of the physical name.

Step 1 — create a new index with the desired mapping:

PUT /products_v2
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 0,
    "refresh_interval": "-1",
    "analysis": {
      "analyzer": {
        "product_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": ["lowercase", "russian_stemmer"]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "id": { "type": "keyword" },
      "title": {
        "type": "text",
        "analyzer": "product_analyzer",
        "fields": {
          "keyword": { "type": "keyword" }
        }
      },
      "price": { "type": "scaled_float", "scaling_factor": 100 },
      "new_field": { "type": "keyword" }
    }
  }
}

During loading, disable replicas and refresh — this speeds up writes by up to 80%.

Launch reindex with parallel slices

Start reindex with slices: auto:

POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "products_v1",
    "size": 500
  },
  "dest": {
    "index": "products_v2",
    "op_type": "create"
  },
  "conflicts": "proceed",
  "slices": "auto"
}

slices: auto splits the task into as many slices as the source index has shards. Each slice runs independently — achieving 5–10x speedup over sequential execution.

Incremental synchronization

While reindexing runs, the application continues to write to the old index. To catch up new data, perform an incremental sync:

POST _reindex?wait_for_completion=false
{
  "source": {
    "index": "products_v1",
    "query": {
      "range": {
        "updated_at": {
          "gte": "now-1h",
          "lte": "now"
        }
      }
    }
  },
  "dest": {
    "index": "products_v2",
    "op_type": "index",
    "version_type": "external"
  }
}

version_type: external uses _version to resolve conflicts. This requires an updated_at field in the mapping.

How to ensure atomic switching?

After reindexing and synchronization complete, run:

# 1. Restore production settings on the new index
PUT /products_v2/_settings
{
  "index.number_of_replicas": 1,
  "index.refresh_interval": "1s"
}

# 2. Wait for replica recovery
curl -u elastic:pw "localhost:9200/_cluster/health/products_v2?wait_for_status=green&timeout=30s"

# 3. Atomically switch the alias
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "products_v2",
        "alias": "products",
        "is_write_index": true
      }
    },
    {
      "remove": {
        "index": "products_v1",
        "alias": "products"
      }
    }
  ]
}

The operation is atomic — no requests are lost. Rollback plan: reverse the alias switch. Do not delete the old index for 24–48 hours. If the new mapping turns out incorrect, simply switch the alias back. All data in the old index remains intact. Optionally, keep a backup of both indices.

Why parallel slices speed up the process dramatically?

Without slices, reindex runs in a single thread. With slices: auto, the task splits into N sub-tasks (by number of source shards). On an index with 5 shards and 100 million documents, reindex takes 6 hours without slices and about 1 hour with them — a 5–6x speedup. Cluster load is balanced evenly.

Data transformation via Painless

If you need to alter the document structure (split fields, normalize prices), use a script in _reindex:

POST _reindex
{
  "source": { "index": "products_v1" },
  "dest": { "index": "products_v2" },
  "script": {
    "source": """
      if (ctx._source.full_name != null) {
        def parts = ctx._source.full_name.splitOnToken(' ');
        ctx._source.first_name = parts[0];
        ctx._source.last_name = parts.length > 1 ? parts[1] : '';
        ctx._source.remove('full_name');
      }
      if (ctx._source.price instanceof String) {
        ctx._source.price = Float.parseFloat(ctx._source.price.replace(',', '.'));
      }
    """,
    "lang": "painless"
  }
}

Step-by-step zero-downtime reindexing

  1. Create a new index with optimized settings (disable replicas and refresh, configure analyzers).
  2. Start reindex with slices: auto — speeds up the process up to 10x.
  3. Perform incremental synchronization to catch up new data.
  4. Restore production settings (replicas, refresh_interval).
  5. Wait for the cluster to reach green status.
  6. Atomically switch the alias — reindexing is complete.

Reindexing stages with aliases

Stage Action Approximate time
1. Preparation Audit current mapping, design new one 1 day
2. Index creation Create new index with settings 10 minutes
3. Data loading Reindex with slices: auto 1–6 hours (depends on volume)
4. Synchronization Incremental sync 10–30 minutes
5. Switch Atomic alias switch 1 second
6. Monitoring Observe for 48 hours post-migration 2 days

What's included

  • Audit of current mapping and data — identify fields needing changes, analyze volumes and access patterns.
  • Design of new mapping — considering analyzers, nested fields, and data types.
  • Migration script development — configure parallel slices, incremental sync, transformation scripts.
  • Execution and monitoring — track progress, speed, errors.
  • Process documentation — describe steps for future reuse.
  • Post-migration support — 48 hours of monitoring after switching.

Contact us to develop a migration plan. Get a consultation for your scenario without downtime.

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.