惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
F
Fortinet All Blogs
Martin Fowler
Martin Fowler
M
MIT News - Artificial intelligence
G
Google Developers Blog
P
Proofpoint News Feed
Recent Announcements
Recent Announcements
MyScale Blog
MyScale Blog
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog
月光博客
月光博客
爱范儿
爱范儿
罗磊的独立博客
腾讯CDC
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
Vercel News
Vercel News
酷 壳 – CoolShell
酷 壳 – CoolShell
B
Blog
C
Check Point Blog
美团技术团队
宝玉的分享
宝玉的分享
Microsoft Security Blog
Microsoft Security Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Part 3: Mastering Lifetimes and Scopes in Go with Parsley
Matthias Fri · 2026-05-16 · via DEV Community

Managing State and Lifecycle in Distributed Systems

In modern Go backend development, managing the lifecycle of a service is as critical as its implementation. For instance, a database connection pool should ideally be shared across the entire application to minimize overhead and maintain connection limits. Conversely, an authentication context or a request-specific logger should only exist for the duration of a single HTTP request to avoid state leakage between users.

In the previous article, Part 2: Mastering Service Registration in Go with Parsley, we discussed how to register services using constructors and pre-existing instances. However, registration is only half the story. The other half is determining when these services are created and how long they persist.

Without a structured dependency injection container, developers often end up passing context.Context everywhere or manually managing global variables—both of which increase complexity and hinder testability. Parsley addresses this by providing explicit control over service lifetimes.

Recap: Singleton vs. Registered Instance

In Part 2, we saw two ways to achieve singleton behavior, but they differ in one key aspect: Activation Timing.

  • Registered Instance (RegisterInstance): This is an eager singleton. You create the object yourself before registration. Parsley simply stores and provides the pre-existing instance. This is useful for third-party clients or legacy objects.
  • Singleton Registration (RegisterSingleton): This is a lazy singleton. You provide a constructor function, and Parsley only calls it the first time the service is requested.

Note: Lazy initialization is generally preferred. It reduces application startup time and ensures that heavy services are only created if they are actually needed by the current execution path.

The Three Pillars of Parsley Lifetimes

Parsley provides three distinct lifetime behaviors to manage your services effectively:

  1. Transient: A new instance is created every time the service is requested. This is ideal for lightweight, stateless objects where you want to ensure a clean state for every consumer.
  2. Scoped: A single instance is created and reused within a specific scope. In a web server, this usually corresponds to a single HTTP request.
  3. Singleton: A single instance is created once and shared throughout the entire application for the lifetime of the resolver.

Architecture: The Role of Scoped Context

The Scoped lifetime is the backbone of request-based architectures. It ensures that all dependencies within a single request—such as a database transaction, a user service, and an audit logger—share the same instance of a request-specific resource.

Parsley manages this by attaching instances to a context.Context. When you create a new scope using resolving.NewScopedContext(ctx), Parsley creates a specialized context that acts as a container for that specific lifecycle.

Practical Example: Observing Service Activation

To demonstrate how lifetimes affect your application, let's create a Greeter service and observe how many times it is instantiated under different scopes.

1. Define the Service

type Greeter interface {
    SayHello(name string)
}

type greeter struct {
    id string
}

func (g *greeter) SayHello(name string) {
    fmt.Printf("Hello, %s! (Instance ID: %s)\n", name, g.id)
}

func NewGreeter() Greeter {
    g := &greeter{}
    // Use the pointer address as a simple unique ID
    g.id = fmt.Sprintf("%p", g)
    fmt.Printf("New Greeter instance activated: %s\n", g.id)
    return g
}

Enter fullscreen mode Exit fullscreen mode

2. Resolve with Scopes

In the following example, we register the Greeter as Scoped. We then resolve it multiple times within two different scopes.

package main

import (
    "context"
    "fmt"
    "github.com/matzefriedrich/parsley/pkg/registration"
    "github.com/matzefriedrich/parsley/pkg/resolving"
)

func main() {
    registry := registration.NewServiceRegistry()

    // Register the constructor with a Scoped lifetime
    _ = registration.RegisterScoped(registry, NewGreeter)

    resolver := resolving.NewResolver(registry)
    ctx := context.Background()

    // --- Scope A ---
    fmt.Println("--- Starting Scope A ---")
    scopeA := resolving.NewScopedContext(ctx)
    g1, _ := resolving.ResolveRequiredService[Greeter](scopeA, resolver)
    g1.SayHello("Alice")

    g2, _ := resolving.ResolveRequiredService[Greeter](scopeA, resolver)
    g2.SayHello("Bob")

    // --- Scope B ---
    fmt.Println("\n--- Starting Scope B ---")
    scopeB := resolving.NewScopedContext(ctx)
    g3, _ := resolving.ResolveRequiredService[Greeter](scopeB, resolver)
    g3.SayHello("Charlie")
}

Enter fullscreen mode Exit fullscreen mode

Output Analysis:

--- Starting Scope A ---
New Greeter instance activated: 0xc0000120a8
Hello, Alice! (Instance ID: 0xc0000120a8)
Hello, Bob! (Instance ID: 0xc0000120a8)

--- Starting Scope B ---
New Greeter instance activated: 0xc0000120b0
Hello, Charlie! (Instance ID: 0xc0000120b0)

Enter fullscreen mode Exit fullscreen mode

Within Scope A, the instance is reused for both "Alice" and "Bob". When we switch to Scope B, Parsley detects a new context and activates a fresh instance.

Operational Considerations

When to Use Transient?

Use transient for services that carry no internal state or are cheap to create. This prevents accidental state leakage between different parts of your application and is the safest default if you are unsure.

When to Use Scoped?

Scoped is the "sweet spot" for backend services. Use it for anything that should be consistent across a single request but isolated from other requests:

  • Database transactions
  • Request-specific loggers with correlation IDs
  • User identity providers

When to Use Singleton?

Use singletons for heavy resources that should persist for the life of the process. Examples include database connection pools (*sql.DB), configuration managers, and external API clients that manage their own internal connection pooling.

Tradeoffs and Limitations

While automated lifetime management reduces boilerplate, it introduces specific engineering responsibilities:

  • Context Hygiene: You must ensure that resolving.NewScopedContext is called at the correct entry points (e.g., in a middleware). If you inadvertently use the root context for all resolutions, your scoped services will effectively behave as singletons.
  • Memory Management: Singletons stay in memory until the Resolver is destroyed. Be cautious about registering large objects as singletons if they are only needed occasionally.
  • Thread Safety: Singleton and Scoped services might be accessed by multiple goroutines concurrently (especially in high-concurrency web servers). Ensure your implementations are thread-safe.

Summary

Understanding lifetimes and scopes is essential for building scalable Go applications. By leveraging Transient, Scoped, and Singleton behaviors, you can ensure that your services are created at the right time and shared only when appropriate, leading to cleaner code and more predictable resource usage.

In the next part of this series, we will explore Advanced Registration Patterns, where we discuss how to organize your services into modules and use custom factory functions.

Next Steps

  • Explore the Lifetime Scopes documentation for more details.
  • Review your application's main.go and determine which services could benefit from a Scoped lifetime.