Resource Management in Effect
Effect provides safe resource management through Scopes and finalizers. This ensures resources like database connections, file handles, and network sockets are properly cleaned up, even when errors occur or effects are interrupted.Effect.acquireRelease Pattern
UseEffect.acquireRelease to manage resources with automatic cleanup:
Composing Services with Resources
When one service depends on another that usesEffect.acquireRelease, the resources are automatically managed:
Layer Lifecycle Management
Layers have a built-in lifecycle. Resources acquired in a layer are automatically released when the layer scope is closed.Background Tasks with Layer.effectDiscard
UseLayer.effectDiscard to create layers that run background tasks without exposing a service:
Scopes and Finalizers
AScope is a context that tracks the lifecycle of resources. Finalizers registered to a scope are guaranteed to run when the scope is closed, even in the presence of errors or interruptions.
Effect.forkScoped
UseEffect.forkScoped to fork a fiber that will be automatically interrupted when the scope closes:
Dynamic Resources with LayerMap
UseLayerMap.Service to dynamically build and manage resources keyed by identifiers:
Best Practices
- Use
Effect.acquireReleasefor any resource that needs cleanup - The acquire phase should be infallible or handle errors appropriately
- The release phase should be infallible (use
Effect.syncor handle errors) - Resources acquired in layers are automatically managed by the layer lifecycle
- Use
Effect.forkScopedfor background tasks that should be tied to a scope - Use
Layer.effectDiscardfor background work without a service interface - Use
LayerMapfor dynamically created resources keyed by identifiers - Always register cleanup logic—Effect guarantees it will run even on interruption