effect-patterns-resource-management
Provides best practices and patterns for resource management in Effect-TS.
Install
mkdir -p .claude/skills/effect-patterns-resource-management && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/9139" && unzip -o skill.zip -d .claude/skills/effect-patterns-resource-management && rm skill.zipInstalls to .claude/skills/effect-patterns-resource-management
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Effect-TS patterns for Resource Management. Use when working with resource management in Effect-TS applications.Key capabilities
- →Bracket resource usage with acquire and release effects
- →Guarantee cleanup logic execution regardless of success, failure, or interruption
- →Manage pools of reusable resources
- →Handle hierarchical resource dependencies with nested scopes
- →Create managed runtimes for scoped services
How it works
The skill uses Effect-TS patterns like `acquireRelease`, `Pool`, and `Layer.scoped` to ensure resources are acquired, used, and released safely, even with interruptions or concurrency.
Inputs & outputs
When to use effect-patterns-resource-management
- →Safely bracket database connections
- →Implement cleanup logic for external resources
- →Standardize resource management in Effect-TS
- →Refactor async/await cleanup to Effect patterns
About this skill
Effect-TS Patterns: Resource Management
This skill provides 8 curated Effect-TS patterns for resource management. Use this skill when working on tasks related to:
- resource management
- Best practices in Effect-TS applications
- Real-world patterns and solutions
🟢 Beginner Patterns
Safely Bracket Resource Usage with acquireRelease
Rule: Bracket the use of a resource between an acquire and a release effect.
Good Example:
import { Effect, Console } from "effect";
// A mock resource that needs to be managed
const getDbConnection = Effect.sync(() => ({ id: Math.random() })).pipe(
Effect.tap(() => Effect.log("Connection Acquired"))
);
const closeDbConnection = (conn: {
id: number;
}): Effect.Effect<void, never, never> =>
Effect.log(`Connection ${conn.id} Released`);
// The program that uses the resource
const program = Effect.acquireRelease(
getDbConnection, // 1. acquire
(connection) => closeDbConnection(connection) // 2. cleanup
).pipe(
Effect.tap((connection) =>
Effect.log(`Using connection ${connection.id} to run query...`)
)
);
Effect.runPromise(Effect.scoped(program));
/*
Output:
Connection Acquired
Using connection 0.12345... to run query...
Connection 0.12345... Released
*/
Explanation:
By using Effect.acquireRelease, the closeDbConnection logic is guaranteed to run after the main logic completes. This creates a self-contained, leak-proof unit of work that can be safely composed into larger programs.
Anti-Pattern:
Using a standard try...finally block with async/await. While it handles success and failure cases, it is not interruption-safe. If the fiber executing the Promise is interrupted by Effect's structured concurrency, the finally block is not guaranteed to run, leading to resource leaks.
// ANTI-PATTERN: Not interruption-safe
async function getUser() {
const connection = await getDbConnectionPromise(); // acquire
try {
return await useConnectionPromise(connection); // use
} finally {
// This block may not run if the fiber is interrupted!
await closeConnectionPromise(connection); // release
}
}
Rationale:
Wrap the acquisition, usage, and release of a resource within an Effect.acquireRelease call. This ensures the resource's cleanup logic is executed, regardless of whether the usage logic succeeds, fails, or is interrupted.
This pattern is the foundation of resource safety in Effect. It provides a composable and interruption-safe alternative to a standard try...finally block. The release effect is guaranteed to execute, preventing resource leaks which are common in complex asynchronous applications, especially those involving concurrency where tasks can be cancelled.
🟡 Intermediate Patterns
Pool Resources for Reuse
Rule: Use Pool to manage expensive resources that can be reused across operations.
Good Example:
import { Effect, Pool, Scope, Duration } from "effect"
// ============================================
// 1. Define a poolable resource
// ============================================
interface DatabaseConnection {
readonly id: number
readonly query: (sql: string) => Effect.Effect<unknown[]>
readonly close: () => Effect.Effect<void>
}
let connectionId = 0
const createConnection = Effect.gen(function* () {
const id = ++connectionId
yield* Effect.log(`Creating connection ${id}`)
// Simulate connection setup time
yield* Effect.sleep("100 millis")
const connection: DatabaseConnection = {
id,
query: (sql) => Effect.gen(function* () {
yield* Effect.log(`[Conn ${id}] Executing: ${sql}`)
return [{ result: "data" }]
}),
close: () => Effect.gen(function* () {
yield* Effect.log(`Closing connection ${id}`)
}),
}
return connection
})
// ============================================
// 2. Create a pool
// ============================================
const makeConnectionPool = Pool.make({
acquire: createConnection,
size: 5, // Maximum 5 connections
})
// ============================================
// 3. Use the pool
// ============================================
const runQuery = (pool: Pool.Pool<DatabaseConnection>, sql: string) =>
Effect.scoped(
Effect.gen(function* () {
// Get a connection from the pool
const connection = yield* pool.get
// Use it
const results = yield* connection.query(sql)
// Connection automatically returned to pool when scope ends
return results
})
)
// ============================================
// 4. Run multiple queries concurrently
// ============================================
const program = Effect.scoped(
Effect.gen(function* () {
const pool = yield* makeConnectionPool
yield* Effect.log("Starting concurrent queries...")
// Run 10 queries with only 5 connections
const queries = Array.from({ length: 10 }, (_, i) =>
runQuery(pool, `SELECT * FROM users WHERE id = ${i}`)
)
const results = yield* Effect.all(queries, { concurrency: "unbounded" })
yield* Effect.log(`Completed ${results.length} queries`)
return results
})
)
Effect.runPromise(program)
Rationale:
Use Pool to manage a collection of reusable resources. The pool handles acquisition, release, and lifecycle management automatically.
Creating resources is expensive:
- Database connections - TCP handshake, authentication
- HTTP clients - Connection setup, TLS negotiation
- Worker threads - Spawn overhead
- File handles - System calls
Pooling amortizes this cost across many operations.
Create a Service Layer from a Managed Resource
Rule: Provide a managed resource to the application context using Layer.scoped.
Good Example:
import { Effect, Console } from "effect";
// 1. Define the service interface
interface DatabaseService {
readonly query: (sql: string) => Effect.Effect<string[], never, never>;
}
// 2. Define the service implementation with scoped resource management
class Database extends Effect.Service<DatabaseService>()("Database", {
// The scoped property manages the resource lifecycle
scoped: Effect.gen(function* () {
const id = Math.floor(Math.random() * 1000);
// Acquire the connection
yield* Effect.log(`[Pool ${id}] Acquired`);
// Setup cleanup to run when scope closes
yield* Effect.addFinalizer(() => Effect.log(`[Pool ${id}] Released`));
// Return the service implementation
return {
query: (sql: string) =>
Effect.sync(() => [`Result for '${sql}' from pool ${id}`]),
};
}),
}) {}
// 3. Use the service in your program
const program = Effect.gen(function* () {
const db = yield* Database;
const users = yield* db.query("SELECT * FROM users");
yield* Effect.log(`Query successful: ${users[0]}`);
});
// 4. Run the program with scoped resource management
Effect.runPromise(
Effect.scoped(program).pipe(Effect.provide(Database.Default))
);
/*
Output:
[Pool 458] Acquired
Query successful: Result for 'SELECT * FROM users' from pool 458
[Pool 458] Released
*/
Explanation:
The Effect.Service helper creates the Database class, which acts as both the service definition and its context key (Tag). The Database.Live layer connects this service to a concrete, lifecycle-managed implementation. When program asks for the Database service, the Effect runtime uses the Live layer to run the acquire effect once, caches the resulting DbPool, and injects it. The release effect is automatically run when the program completes.
Anti-Pattern:
Creating and exporting a global singleton instance of a resource. This tightly couples your application to a specific implementation, makes testing difficult, and offers no guarantees about graceful shutdown.
// ANTI-PATTERN: Global singleton
export const dbPool = makeDbPoolSync(); // Eagerly created, hard to test/mock
function someBusinessLogic() {
// This function has a hidden dependency on the global dbPool
return dbPool.query("SELECT * FROM products");
}
Rationale:
Define a service using class MyService extends Effect.Service(...). Implement the service using the scoped property of the service class. This property should be a scoped Effect (typically from Effect.acquireRelease) that builds and releases the underlying resource.
This pattern is the key to building robust, testable, and leak-proof applications in Effect. It elevates a managed resource into a first-class service that can be used anywhere in your application. The Effect.Service helper simplifies defining the service's interface and context key. This approach decouples your business logic from the concrete implementation, as the logic only depends on the abstract service. The Layer declaratively handles the resource's entire lifecycle, ensuring it is acquired lazily, shared safely, and released automatically.
Compose Resource Lifecycles with Layer.merge
Rule: Compose multiple scoped layers using Layer.merge or by providing one layer to another.
Good Example:
import { Effect, Layer, Console } from "effect";
// --- Service 1: Database ---
interface DatabaseOps {
query: (sql: string) => Effect.Effect<string, never, never>;
}
class Database extends Effect.Service<DatabaseOps>()("Database", {
sync: () => ({
query: (sql: string): Effect.Effect<string, never, never> =>
Effect.sync(() => `db says: ${sql}`),
}),
}) {}
// --- Service 2: API Client ---
interface ApiClientOps {
fetch: (path: string) => Effect.Effect<string, never, never>;
}
class ApiClient extends Effect.Service<ApiClientOps>()("ApiClient", {
sync: () => ({
fetch: (path: string): Effect.Effect<string, never, never> =>
Effect.sync(() => `api says: ${path}`),
}),
}) {}
// --- Application Layer ---
// W
---
*Content truncated.*
When not to use it
- →Using a standard try...finally block with async/await for interruption-safe cleanup
- →Using Layer.toRuntime with layers containing scoped resources
Limitations
- →The finally block in async/await is not guaranteed to run if the fiber is interrupted
- →Layer.toRuntime will acquire resources but has no mechanism to release them
How it compares
This skill provides interruption-safe and composable resource management patterns for Effect-TS, which is different from standard try...finally blocks in async/await.
Compared to similar skills
effect-patterns-resource-management side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| effect-patterns-resource-management (this skill) | 0 | 7mo | No flags | Advanced |
| typescript-expert | 10 | 6mo | Review | Advanced |
| agent-coder | 3 | 6mo | No flags | Intermediate |
| functional | 3 | 2mo | No flags | Intermediate |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by PaulJPhilp
View all by PaulJPhilp →You might also like
typescript-expert
davila7
TypeScript and JavaScript expert with deep knowledge of type-level programming, performance optimization, monorepo management, migration strategies, and modern tooling. Use PROACTIVELY for any TypeScript/JavaScript issues including complex type gymnastics, build performance, debugging, and architectural decisions. If a specialized expert is a better fit, I will recommend switching and stop.
agent-coder
ruvnet
Agent skill for coder - invoke with $agent-coder
functional
citypaul
Functional programming patterns with immutable data. Use when writing logic or data transformations.
modern-javascript-patterns
sickn33
Master ES6+ features including async/await, destructuring, spread operators, arrow functions, promises, modules, iterators, generators, and functional programming patterns for writing clean, efficient JavaScript code. Use when refactoring legacy code, implementing modern patterns, or optimizing JavaScript applications.
migrate-honcho-ts
plastic-labs
Migrates Honcho TypeScript SDK code from v1.6.0 to v2.0.0. Use when upgrading @honcho-ai/sdk, fixing breaking changes after upgrade, or when errors mention removed APIs like .core, getConfig, observations, or snake_case properties.
agent-implementer-sparc-coder
ruvnet
Agent skill for implementer-sparc-coder - invoke with $agent-implementer-sparc-coder