Skip to content

Sharing Entity instances across multiple Services with different clients causes client overwrite #547

@anatolzak

Description

@anatolzak

Describe the bug

When the same Entity instance is added to multiple Service instances that have different DynamoDB clients configured, the client from the last Service overwrites the client for all Services sharing that Entity.

Reproduction:

import { Entity, Service } from 'electrodb'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

const taskEntity = new Entity({
  model: { entity: 'task', service: 'myapp', version: '1' },
  attributes: { id: { type: 'string' } },
  indexes: { primary: { pk: { field: 'pk', composite: ['id'] } } }
});

// Two different DynamoDB clients (e.g., different regions or accounts)
const clientA = new DynamoDBClient({ region: 'us-east-1' });
const clientB = new DynamoDBClient({ region: 'eu-west-1' });

const entities = {
  task: taskEntity,
};

const serviceA = new Service(entities, { client: clientA });
const serviceB = new Service(entities, { client: clientB });

// Expected: serviceA uses clientA, serviceB uses clientB
// Actual: Both services use clientB
console.log(serviceA.entities.task.client === serviceB.entities.task.client); // true (unexpected)

Expected behavior:

Each Service should maintain isolated client configuration. Operations through serviceA should use clientA, and operations through serviceB should use clientB.

Actual behavior:

The join() method calls entity.setClient() which mutates the Entity instance directly. Since both Services reference the same Entity instance, whichever Service joins last overwrites the client for all Services.

Root cause:

In service.js, the join() method (line 264-266) calls entity.setClient(options.client) on the passed Entity instance rather than creating a copy:

if (options.client) {
  entity.setClient(options.client);
}

Use case:

I need to use the same Entity definitions across multiple Services that connect to different DynamoDB tables/regions/accounts (e.g., for multi-tenancy, cross-region replication, or migration scenarios).

ElectroDB Version
3.5.3

Here is a minimal repo reproducing this issue
https://github.com/anatolzak/electrodb-dynamo-client-bug/blob/main/index.ts

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions