How Service Profiling Works in fabrica-kit Using the profile Package

Service profiling in fabrica-kit centralizes runtime identity through the profile package, which initializes global state via profile.Init and exposes deployment metadata through zero-cost accessor functions.

The go-pantheon/fabrica-kit library provides a lightweight mechanism for service discovery and environment configuration through its profile package. This subsystem acts as the single source of truth for runtime identity, allowing services to broadcast their name, version, environment, and zone consistently across logs, metrics, and inter-service communication.

Core Architecture of the profile Package

The profile package is organized into focused source files that separate state management, environment definitions, and utility functions.

Global State Management in vars.go

The file profile/vars.go holds the mutable global state that represents the current service instance. It declares package-level variables including _serviceName, _profile, _color, _version, _nodeName, and _zone. The Init function populates these variables during application bootstrap, and accessor functions provide read-only access to the rest of the codebase.

// profile/vars.go - Initialization signature
func Init(serviceName, profileStr, color string, zone uint32, version, nodeName string)

Environment Profile Definitions in profile.go

The file profile/profile.go defines three supported environment profiles as constants: ProfileDev, ProfileTest, and ProfileProd. It exports predicate helpers including IsDev(), IsTest(), and IsProd() that allow conditional logic based on the current deployment environment.

Canonical Metadata Keys in metadata.go

The file profile/metadata.go declares standardized keys used when exporting profile data to external systems. These include OrgPrefix, VersionKey, ProfileKey, ServiceKey, ColorKey, NodeKey, and ZoneKey, ensuring consistent schema across logs and metrics.

Initializing Service Identity with profile.Init

During application bootstrap, services must call profile.Init early in the execution flow to populate the global state. This is typically invoked in main() using values from environment variables or configuration sources.

package main

import (
	"os"
	"github.com/go-pantheon/fabrica-kit/profile"
)

func main() {
	profile.Init(
		os.Getenv("PANTHEON_SVC"),      // service name
		os.Getenv("PANTHEON_PROFILE"),  // dev|test|prod
		os.Getenv("PANTHEON_COLOR"),    // e.g., "local"
		1,                              // numeric zone ID
		"v1.3.7+git",                   // build version
		os.Getenv("PANTHEON_NODE"),     // unique node identifier
	)
}

After initialization, the package exposes the configured values through accessor functions that provide zero-runtime-cost lookups.

Runtime Configuration Accessors

The profile package exports read-only accessor functions that allow any component to retrieve the service's runtime identity. These functions return the values set during Init:

  • profile.ServiceName() – returns the service identifier
  • profile.Profile() – returns the environment string (dev, test, or prod)
  • profile.Color() – returns the deployment color (e.g., "local")
  • profile.Version() – returns the build version
  • profile.NodeName() – returns the unique node identifier
  • profile.Zone() – returns the numeric zone ID
// Example accessor implementation from profile/vars.go
func Profile() string { return _profile }

Environment-Aware Predicates

Services can determine their runtime environment using boolean predicate functions exported by the package. These enable feature toggling and conditional behavior without hard-coding environment checks.

if profile.IsDev() {
	// Enable verbose logging or debug endpoints
}

if profile.IsLocal() {
	// Route traffic to local mock services
}

// Available predicates:
// profile.IsDev(), profile.IsTest(), profile.IsProd()
// profile.IsLocal() (defined in profile/color.go)

The IsLocal() predicate specifically checks the color assignment defined in profile/color.go, which is used for routing traffic between color-specific nodes during local development or canary deployments.

Practical Implementation Patterns

Service Bootstrap with Environment Detection

A complete initialization pattern reads environment variables and configures service behavior accordingly:

func main() {
	profile.Init(
		os.Getenv("PANTHEON_SVC"),
		os.Getenv("PANTHEON_PROFILE"),
		os.Getenv("PANTHEON_COLOR"),
		uint32(zoneID),
		version,
		nodeName,
	)

	if profile.IsDev() {
		setupDebugLogging()
	}
	
	// Start HTTP server
}

Standardized Metadata Export

When emitting logs or traces, use the canonical keys from profile/metadata.go to ensure consistent tagging across the infrastructure:

log := logger.WithFields(map[string]any{
	profile.ServiceKey: profile.ServiceName(),
	profile.ProfileKey: profile.Profile(),
	profile.VersionKey: profile.Version(),
	profile.ColorKey:   profile.Color(),
	profile.NodeKey:    profile.NodeName(),
	profile.ZoneKey:    profile.Zone(),
})
log.Info("service started")

HTTP Client Configuration

Services should use the default HTTP client constants defined in profile/http.go to ensure consistent network behavior across the fleet:

client := &http.Client{
	Timeout: profile.ClientTimeout,
	Transport: &http.Transport{
		MaxIdleConns: profile.ClientMaxIdleConns,
	},
}

Administrative Utilities

The file profile/admin.go provides helper functions for common administrative tasks. For example, PageStartLimit calculates pagination offsets based on configured defaults:

func listItems(page, size int64) ([]Item, error) {
	start, limit := profile.PageStartLimit(page, size)
	return db.QueryItems(start, limit)
}

Summary

  • Single source of truth: The profile package centralizes all runtime identity data, making service configuration auditable and consistent.
  • Zero-cost abstraction: Profile data is stored in package-level variables accessed via simple function calls with minimal overhead.
  • Environment predicates: Functions like IsDev(), IsProd(), and IsLocal() enable conditional logic without magic string comparisons.
  • Standardized metadata: Constants in profile/metadata.go eliminate "magic strings" when exporting data to observability platforms.
  • Cross-service consistency: HTTP defaults and administrative helpers ensure uniform behavior across all services using fabrica-kit.

Frequently Asked Questions

What happens if profile.Init is called multiple times?

Each call to profile.Init overwrites the package-level variables in profile/vars.go with new values. While the package does not guard against multiple initializations, services should call Init exactly once during bootstrap to avoid race conditions or inconsistent state.

How do I determine if the service is running in a production environment?

Use the profile.IsProd() predicate function defined in profile/profile.go. This returns true when the initialized profile equals the ProfileProd constant, allowing you to gate production-specific features or disable debug endpoints.

What is the purpose of the "color" assignment in service profiling?

The color assignment (accessed via profile.Color() and profile.IsLocal()) supports traffic routing and deployment strategies such as blue-green deployments or local development isolation. When a service reports IsLocal() as true, it typically indicates the instance should route requests to local mock services rather than remote dependencies.

Where does fabrica-kit define default timeouts for HTTP clients?

Default HTTP client configuration values including ClientTimeout and ClientMaxIdleConns are defined in profile/http.go. Services should reference these constants when constructing http.Client instances to ensure consistent timeout behavior across the service mesh.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →