npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

elastic-shard-router

v0.2.3

Published

A TypeScript Node.js library to generate, verify, and map deterministic Elasticsearch routing keys to specific shards, enabling precise document placement and retrieval.

Downloads

34

Readme

elastic-shard-router

A TypeScript Node.js library to generate, verify, and map deterministic Elasticsearch routing keys to specific shards, enabling precise document placement and retrieval.

What is this library for?

elastic-shard-router is designed to help you control and understand how documents are routed to shards in an Elasticsearch index. It allows you to:

  • Generate deterministic routing keys for each shard, so you know exactly which shard a document will be stored in.
  • Implement strict multi-tenant isolation by assigning tenants to specific shards and always using the correct routing key for each tenant.
  • Support custom tenant-to-shard allocation strategies (e.g., round-robin, least-loaded, or your own logic).
  • Verify and calculate shard assignments for any routing key, making migrations and audits easy.

This is especially useful for:

  • Multi-tenant SaaS platforms that want to guarantee tenant data isolation at the shard level.
  • Performance optimization by controlling document distribution across shards.
  • Data migration, rebalancing, or compliance scenarios where deterministic routing is required.

API Reference

ShardRouter Constructor

new ShardRouter(
  esClient: ElasticsearchClient,
  indexName: string,
  prefix?: string,
  suffix?: string,
  tenantDistributionAlgo?: (
    tenantId: string,
    tenantShardMap: Map<string, number>,
    shardTenantMap: Map<number, string[]>,
    numberOfShards: number
  ) => number
)

Parameters:

  • esClient (required): Elasticsearch client instance from @elastic/elasticsearch.
  • indexName (required): Name of the Elasticsearch index.
  • prefix (optional): String to prepend to all generated routing keys (default: '').
  • suffix (optional): String to append to all generated routing keys (default: '').
  • tenantDistributionAlgo (optional): Custom function to control tenant-to-shard assignment. Receives the tenant ID, current tenant-to-shard and shard-to-tenant mappings, and the number of shards. Should return the shard number to assign the tenant to. Defaults to round-robin allocation.

getRoutingKeyForTenant(tenantId: string): string | undefined

Returns the routing key for a given tenant, allocating the tenant to a shard if not already assigned. This is the recommended way to route multi-tenant data.

Usage:

const router = new ShardRouter(esClient, 'your-index', 'key-');
await router.initialize();
const routingKey = router.getRoutingKeyForTenant('tenantA');
await esClient.index({
  index: 'your-index',
  routing: routingKey,
  body: { tenantId: 'tenantA', data: 'Tenant A data' }
});

getAllRoutingKeys(): Map<number, string>

Returns all precomputed routing keys as a Map with shard numbers as keys. Useful for bulk operations or direct shard access.

Usage:

const allKeys = router.getAllRoutingKeys();
for (const [shardNum, routingKey] of allKeys) {
  // Use routingKey for direct shard operations
}

Other Methods (simple descriptions)

  • initialize(): Promise
    Loads index metadata and precomputes routing keys. Must be called before using routing methods.

  • getRoutingKeyForShard(shardNumber: number): string | undefined
    Returns the precomputed routing key for a specific shard.

  • verifyRoutingKey(routingKey: string, expectedShard: number): boolean
    Checks if a routing key maps to the expected shard.

  • calculateShardForRoutingKey(routingKey: string): number
    Calculates which shard a routing key will route to.

  • getShardTenantMapping(): Map<number, string[]>
    Returns the current mapping of shard numbers to arrays of tenant IDs.

Examples

See the examples/ directory for detailed usage patterns, including multi-tenant allocation, bulk indexing, and migration scenarios.