Common Issues & Troubleshooting
This guide covers common issues you might encounter when using CNStra and how to resolve them.
Concurrency Scope: Per-CNS Instance
Important: Concurrency limits in CNStra work at the level of one CNS instance in one process. Each CNS instance maintains its own independent concurrency gates.
Understanding Instance-Level Concurrency
Setup shared by the examples on this page
import { Inject, Module } from '@nestjs/common';
import { CNS, collateral, neuron } from '@cnstra/core';
import type { TCNSNeuron } from '@cnstra/types';
type TTask = { id: string };
const task = collateral<TTask>();
const request = collateral<{ url: string }>();
const output = collateral<unknown>();
const workerNeuron = neuron({}).dendrite({ collateral: task, response: () => {} });
const apiWorker = neuron({}).dendrite({ collateral: request, response: () => {} });
const otherNeuron = neuron({
signal1: collateral<{ id: string }>(),
signal2: collateral<{ count: number }>(),
});
const signal = task.createSignal({ id: '1' });
declare const cns: CNS<TCNSNeuron>;
declare function processTask(task: TTask): Promise<unknown>;
declare function callExternalAPI(request: { url: string }): Promise<unknown>;
When you set a concurrency limit on a neuron using neuron.setConcurrency(n), that limit applies only within a single CNS instance. If you create multiple CNS instances, each will have its own separate concurrency control.
// First CNS instance
const cns1 = new CNS([workerNeuron.setConcurrency(2)]);
// This instance allows max 2 concurrent executions of workerNeuron
// Second CNS instance (separate process or module)
const cns2 = new CNS([workerNeuron.setConcurrency(2)]);
// This instance ALSO allows max 2 concurrent executions
// But these limits are INDEPENDENT - total could be 4 concurrent executions
Multiple Instances in NestJS
If you create multiple CNS instances in a NestJS application (e.g., in different modules), each instance will have its own independent concurrency gates:
// Module A
@Module({})
export class ModuleA {
private cnsA = new CNS([
apiWorker.setConcurrency(5)
]);
}
// Module B
@Module({})
export class ModuleB {
private cnsB = new CNS([
apiWorker.setConcurrency(5) // Same neuron, but different instance
]);
}
Result: You could have up to 10 concurrent executions of apiWorker (5 per instance), not 5 total.
Why This Matters
This behavior is important when:
-
Rate limiting external APIs: If you set
concurrency: 5to limit API calls, but create 3 CNS instances, you could end up with 15 concurrent calls instead of 5. -
Resource management: Database connection pools, file handles, or other limited resources might be exhausted if multiple instances each allow their own concurrency.
-
Shared resource contention: If multiple instances access the same external service, the effective concurrency is the sum of all instance limits.
Solutions
Option 1: Single CNS Instance (Recommended)
Create one shared CNS instance and inject it where needed:
// cns.module.ts
@Module({
providers: [
{
provide: 'CNS',
useFactory: () => new CNS([
workerNeuron.setConcurrency(5)
])
}
],
exports: ['CNS']
})
export class CNSModule {}
// other.module.ts
@Module({
imports: [CNSModule]
})
export class OtherModule {
constructor(@Inject('CNS') private readonly cns: CNS<TCNSNeuron>) {}
}
Option 2: Coordinate Concurrency Across Instances
If you must use multiple instances, coordinate concurrency limits externally:
// Use a shared semaphore or rate limiter
import { RateLimiter } from 'limiter';
const sharedLimiter = new RateLimiter({
tokensPerInterval: 5,
interval: 'second'
});
const rateLimitedWorker = neuron({ output })
.dendrite({
collateral: task,
response: async (payload, axon) => {
await sharedLimiter.removeTokens(1);
// Now process with shared limit
return axon.output.createSignal(await processTask(payload));
}
});
Option 3: Use External Queue Systems
For production systems, use external queue systems (BullMQ, RabbitMQ, AWS SQS) that provide process-wide or distributed concurrency control:
import { Queue, Worker } from 'bullmq';
const connection = { host: 'localhost', port: 6379 };
// Single queue with process-wide concurrency control
const queue = new Queue('jobs', { connection });
const worker = new Worker('jobs', async (job) => {
const stimulation = cns.stimulate(task.createSignal(job.data));
await stimulation.waitUntilComplete();
}, {
connection,
concurrency: 5 // This applies across all workers in the process
});
See Integrations for more details. For best practices on context usage, see Best Practices.
Memory Issues
Large Payloads in Queue
If your signal payloads are large and queues grow, memory usage can spike. See Performance for detailed guidance on managing memory.
Quick fix: Keep payloads small, use references (IDs) instead of full objects.
Passing State Between Neurons
CNStra has no mutable per-neuron store — all per-run state flows through signal payloads (dependencies such as a store come from a factory function). If you need a value downstream, put it on the outgoing signal:
const step = collateral<{ data: string; attempt?: number }>();
const next = collateral<{ result: string; attempt: number }>();
const stepNeuron = neuron({ next }).dendrite({
collateral: step,
response: async (payload, axon) => {
// All per-run data (including counters/correlation ids) rides on the payload.
return axon.next.createSignal({ result: payload.data, attempt: (payload.attempt ?? 0) + 1 });
}
});
Stimulation Not Completing
Infinite Loops
If your neuron graph has cycles and no termination condition, stimulations can run indefinitely.
Solution: Set maxNeuronHops to prevent runaway processing:
const stimulation = cns.stimulate(signal, {
maxNeuronHops: 100 // Stop after 100 hops
});
Errors Not Being Handled
If a dendrite throws and nothing observes the run, the failure is silent: stimulate() returns a CNSStimulation (not a Promise), the completion Promise is created lazily by waitUntilComplete(), and with no response listener the error is caught internally onto response.error but never logged, thrown, or even raised as an unhandled rejection. The symptom is usually "no output / nothing happened" (sometimes a run that looks stuck) — not an error in the console.
Solution: observe every run with a global listener, or await completion (a dendrite throw rejects waitUntilComplete() even with no listener). See Error Handling for the full picture.
// A) Global listener — surfaces failures from every stimulation (fire-and-forget safe)
cns.addResponseListener((r) => {
if (r.error) console.error('Error:', r.error);
});
// B) Or await the run and catch its rejection
await cns.stimulate(signal).waitUntilComplete();
Type Safety Issues
Missing Collateral Bindings
If you forget to bind a collateral, TypeScript will catch it at compile time (with exhaustive binding).
Solution: Use exhaustive binding so that all collaterals are handled:
const listener = neuron({}).bind(otherNeuron.axon, {
signal1: (p) => { /* ... */ },
signal2: (p) => { /* ... */ },
// TypeScript will error if signal3 is missing
});
Performance Issues
Too Many Concurrent Stimulations
Creating thousands of stimulations simultaneously can overwhelm the system.
Solution: Use external queue systems or batch processing. See Performance for optimization strategies.
Slow External APIs
If external APIs are slow and you have high concurrency, you might exhaust connection pools or hit rate limits.
Solution: Set appropriate per-neuron concurrency limits:
const apiNeuron = neuron({ output })
.setConcurrency(10) // Limit concurrent API calls
.dendrite({
collateral: request,
response: async (payload, axon) => {
const result = await callExternalAPI(payload);
return axon.output.createSignal(result);
}
});
Getting Help
If you encounter issues not covered here:
- Check the API documentation for correct usage
- Review Performance guide for optimization tips
- See Recipes for common patterns
- Open an issue on GitHub