akka-net-management

Akka.Management para bootstrapping de cluster, descoberta de serviços (Kubernetes, Azure, Config), verificações de integridade e formação dinâmica de cluster sem nós seed estáticos.

O que é akka-net-management?

Esta skill fornece uma solução completa para configurar o Akka.Management e o Akka.Cluster.Bootstrap, permitindo a formação dinâmica de clusters sem depender de nós seed estáticos. Ela é essencial para implantações em ambientes como Kubernetes e Azure, onde os endereços dos nós podem mudar dinamicamente. A skill cobre a configuração de provedores de descoberta (Kubernetes, Azure Table Storage e Config HOCON), endpoints de health check e integração com Akka.Hosting e .NET Aspire. Com esta configuração, os nós do cluster podem se descobrir automaticamente, formando um cluster coeso e resiliente em infraestruturas elásticas e de auto-scaling. A documentação incluída aborda desde a instalação dos pacotes NuGet até a solução de problemas comuns, como falhas na formação do cluster e split brain.

Funciona com~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/akka-management

Installed? Explore more Programação e Desenvolvimento skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Gerenciamento e Descoberta de Serviços Akka.NET

Quando Usar Esta Skill

Use esta skill quando:

  • Implantar clusters Akka.NET no Kubernetes ou em ambientes de nuvem
  • Substituir nós seed estáticos por descoberta dinâmica de serviços
  • Configurar bootstrap de cluster para formação automática
  • Configurar endpoints de integridade para balanceadores de carga
  • Integrar com Azure Table Storage, API Kubernetes ou descoberta baseada em configuração

Arquivos de Referência

Visão Geral

Akka.Management fornece endpoints HTTP para gerenciamento de cluster e integra-se com Akka.Cluster.Bootstrap para permitir a formação dinâmica de clusters usando descoberta de serviços em vez de nós seed estáticos.

Por que Usar Akka.Management?

AbordagemPrósContras
Nós Seed EstáticosSimples, sem dependênciasNão escala, requer IPs conhecidos
Akka.ManagementDescoberta dinâmica, escala para N nósMais configuração, dependências externas

Use nós seed estáticos para: Desenvolvimento, implantações de nó único, infraestrutura fixa.

Use Akka.Management para: Kubernetes, grupos de auto-scaling, ambientes dinâmicos, clusters em produção.


Arquitetura

┌─────────────────────────────────────────────────────────────┐
│                    Cluster Bootstrap                         │
│  ┌─────────────┐    ┌─────────────┐    ┌─────────────┐     │
│  │  Node 1     │    │  Node 2     │    │  Node 3     │     │
│  │             │    │             │    │             │     │
│  │ Management  │◄──►│ Management  │◄──►│ Management  │     │
│  │ HTTP :8558  │    │ HTTP :8558  │    │ HTTP :8558  │     │
│  └──────┬──────┘    └──────┬──────┘    └──────┬──────┘     │
│         │                  │                  │             │
│         └──────────────────┼──────────────────┘             │
│                            │                                │
│                    ┌───────▼───────┐                        │
│                    │   Provedor    │                        │
│                    │  Descoberta   │                        │
│                    └───────────────┘                        │
│                            │                                │
└────────────────────────────┼────────────────────────────────┘
                             │
              ┌──────────────┼──────────────┐
              │              │              │
        ┌─────▼─────┐ ┌──────▼─────┐ ┌─────▼──────┐
        │ Kubernetes│ │   Azure    │ │   Config   │
        │    API    │ │   Tables   │ │   (HOCON)  │
        └───────────┘ └────────────┘ └────────────┘

Pacotes NuGet Necessários

<ItemGroup>
  <!-- Gerenciamento principal -->
  <PackageReference Include="Akka.Management" />
  <PackageReference Include="Akka.Management.Cluster.Bootstrap" />

  <!-- Escolha UM provedor de descoberta -->
  <PackageReference Include="Akka.Discovery.KubernetesApi" />    <!-- Para Kubernetes -->
  <PackageReference Include="Akka.Discovery.Azure" />            <!-- Para Azure -->
  <PackageReference Include="Akka.Discovery.Config.Hosting" />   <!-- Para configuração estática -->
</ItemGroup>

Configuração Akka.Hosting

Configuração Básica com Seleção de Modo

public static class AkkaConfiguration
{
    public static IServiceCollection ConfigureAkka(
        this IServiceCollection services,
        Action<AkkaConfigurationBuilder, IServiceProvider>? additionalConfig = null)
    {
        services.AddOptions<AkkaSettings>()
            .BindConfiguration("AkkaSettings")
            .ValidateDataAnnotations()
            .ValidateOnStart();

        return services.AddAkka("MySystem", (builder, sp) =>
        {
            var settings = sp.GetRequiredService<IOptions<AkkaSettings>>().Value;
            var configuration = sp.GetRequiredService<IConfiguration>();

            ConfigureNetwork(builder, settings, configuration);
            ConfigureHealthChecks(builder);

            additionalConfig?.Invoke(builder, sp);
        });
    }

    private static void ConfigureNetwork(
        AkkaConfigurationBuilder builder,
        AkkaSettings settings,
        IConfiguration configuration)
    {
        if (settings.ExecutionMode == AkkaExecutionMode.LocalTest)
            return;

        builder.WithRemoting(settings.RemoteOptions);

        if (settings.ClusterBootstrapOptions.Enabled)
            ConfigureAkkaManagement(builder, settings, configuration);
        else
            builder.WithClustering(settings.ClusterOptions);
    }
}

Configuração do Akka.Management

private static void ConfigureAkkaManagement(
    AkkaConfigurationBuilder builder,
    AkkaSettings settings,
    IConfiguration configuration)
{
    var mgmtOptions = settings.AkkaManagementOptions;
    var bootstrapOptions = settings.ClusterBootstrapOptions;

    // IMPORTANTE: Limpar nós seed ao usar Akka.Management
    settings.ClusterOptions.SeedNodes = [];

    builder
        .WithClustering(settings.ClusterOptions)
        .WithAkkaManagement(setup =>
        {
            setup.Http.HostName = mgmtOptions.HostName;
            setup.Http.Port = mgmtOptions.Port;
            setup.Http.BindHostName = "0.0.0.0";
            setup.Http.BindPort = mgmtOptions.Port;
        })
        .WithClusterBootstrap(options =>
        {
            options.ContactPointDiscovery.ServiceName = bootstrapOptions.ServiceName;
            options.ContactPointDiscovery.PortName = bootstrapOptions.PortName;
            options.ContactPointDiscovery.RequiredContactPointsNr = bootstrapOptions.RequiredContactPointsNr;
            options.ContactPointDiscovery.Interval = bootstrapOptions.ContactPointProbingInterval;
            options.ContactPointDiscovery.StableMargin = bootstrapOptions.StableMargin;
            options.ContactPointDiscovery.ContactWithAllContactPoints = bootstrapOptions.ContactWithAllContactPoints;
            options.ContactPoint.FilterOnFallbackPort = bootstrapOptions.FilterOnFallbackPort;
            options.ContactPoint.ProbeInterval = bootstrapOptions.BootstrapperDiscoveryPingInterval;
        });

    // Configurar o provedor de descoberta
    ConfigureDiscovery(builder, settings, configuration);
}

Veja discovery-providers.md para o código completo de configuração de descoberta Config, Kubernetes e Azure.

Veja configuration-reference.md para as classes de modelo de configuração fortemente tipadas.


Endpoints de Integridade

O Akka.Management expõe endpoints de integridade para balanceadores de carga e orquestradores:

EndpointFinalidadeRetorna 200 Quando
/aliveVivacidadeActorSystem está em execução
/readyProntidãoMembro do cluster está Up
/cluster/membersDepuraçãoRetorna a associação do cluster

Integração com Health Checks do ASP.NET Core

// Registrar health checks do Akka
builder.Services.AddHealthChecks();

// Na configuração do Akka
builder
    .WithActorSystemLivenessCheck()     // Adiciona o health check "akka-liveness"
    .WithAkkaClusterReadinessCheck();   // Adiciona o health check "akka-cluster-readiness"

// Mapear endpoints
app.MapHealthChecks("/health/live", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("liveness")
});

app.MapHealthChecks("/health/ready", new HealthCheckOptions
{
    Predicate = check => check.Tags.Contains("readiness")
});

Solução de Problemas

Cluster Não se Forma

Sintomas: Nós permanecem como clusters separados de nó único.

Checklist:

  1. Todos os nós usam o mesmo ServiceName
  2. RequiredContactPointsNr corresponde ao número real de réplicas
  3. O provedor de descoberta está configurado corretamente
  4. A rede permite tráfego na porta de gerenciamento (8558)
  5. Para Kubernetes: Permissões RBAC estão configuradas

Split Brain

Sintomas: Múltiplos clusters se formam em vez de um.

Soluções:

  1. Definir ContactWithAllContactPoints = true
  2. Aumentar StableMargin para ambientes mais lentos
  3. Para Aspire: Definir FilterOnFallbackPort = false (portas dinâmicas)
  4. Para Kubernetes: Definir FilterOnFallbackPort = true (portas fixas)

Problemas com Descoberta Azure

Sintomas: Nós não conseguem se encontrar via Azure Tables.

Checklist:

  1. A string de conexão é válida
  2. A conta de armazenamento permite operações de tabela
  3. Todos os nós usam o mesmo ServiceName
  4. O firewall permite acesso ao Azure Storage

Integração com Aspire

Para padrões específicos do Aspire, veja a skill akka-net-aspire-configuration.

Referência rápida para Aspire:

// No AppHost
appBuilder
    .WithEndpoint(name: "remote", protocol: ProtocolType.Tcp,
        env: "AkkaSettings__RemoteOptions__Port")
    .WithEndpoint(name: "management", protocol: ProtocolType.Tcp,
        env: "AkkaSettings__AkkaManagementOptions__Port")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__Enabled", "true")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__DiscoveryMethod", "AzureTableStorage")
    .WithEnvironment("AkkaSettings__ClusterBootstrapOptions__FilterOnFallbackPort", "false");

Resumo: Quando Usar o Quê

CenárioMétodo de DescobertaFilterOnFallbackPort
Desenvolvimento local (nó único)Nenhum (usar nós seed)N/A
Aspire multi-nóAzureTableStoragefalse
KubernetesKubernetestrue
VMs/VMSS AzureAzureTableStoragetrue
Infraestrutura fixaConfigtrue
AWS ECS/EC2Plugins de descoberta AWStrue

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

marketplace-publishing

Workflow for publishing skills and agents to the dotnet-skills Claude Code marketplace. Covers adding new content, updating plugin.json, validation, and release tagging.

Habilidades Relacionadas