LockFree.EventStore 1.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package LockFree.EventStore --version 1.0.2
                    
NuGet\Install-Package LockFree.EventStore -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="LockFree.EventStore" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="LockFree.EventStore" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="LockFree.EventStore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add LockFree.EventStore --version 1.0.2
                    
#r "nuget: LockFree.EventStore, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package LockFree.EventStore@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=LockFree.EventStore&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=LockFree.EventStore&version=1.0.2
                    
Install as a Cake Tool

LockFree.EventStore

Event store em memória, genérico, de baixa latência e lock-free para .NET. Ideal para cenários de monitoramento, métricas e eventos de domínio.

Principais Recursos

  • Escrita MPMC lock-free com descarte FIFO
  • Particionamento por chave para alta concorrência
  • Snapshots consistentes sem bloquear produtores
  • Agregações funcionais e consultas por janela temporal
  • Zero dependências externas, pronto para AOT/Trimming
  • API fluente para configuração avançada
  • Métricas e observabilidade integradas
  • Agregações especializadas (Sum, Average, Min, Max)

Exemplo de Uso Básico

var store = new EventStore<Order>();
store.TryAppend(new Order { Id = 1, Amount = 10m, Timestamp = DateTime.UtcNow });

var total = store.Aggregate(() => 0m, (acc, e) => acc + e.Amount,
    from: DateTime.UtcNow.AddMinutes(-10));

Novos Construtores

// Capacidade explícita
var store = new EventStore<Order>(capacity: 100_000);

// Capacidade e partições
var store = new EventStore<Order>(capacity: 50_000, partitions: 8);

// Configuração avançada
var store = new EventStore<Order>(new EventStoreOptions<Order>
{
    Capacity = 100_000,
    Partitions = 16,
    OnEventDiscarded = evt => Logger.LogTrace("Event discarded: {Event}", evt),
    OnCapacityReached = () => Metrics.IncrementCounter("eventstore.capacity_reached"),
    TimestampSelector = new OrderTimestampSelector()
});

// API fluente
var store = EventStore.For<Order>()
    .WithCapacity(100_000)
    .WithPartitions(8)
    .OnDiscarded(evt => Log(evt))
    .OnCapacityReached(() => NotifyAdmin())
    .WithTimestampSelector(new OrderTimestampSelector())
    .Create();

Propriedades de Estado

store.Count          // Número atual de eventos
store.Capacity       // Capacidade máxima configurada
store.IsEmpty        // Se está vazio
store.IsFull         // Se atingiu capacidade máxima
store.Partitions     // Número de partições

Agregações Especializadas

// Contagem por janela temporal
var count = store.Count(from: start, to: end);

// Soma de valores
var sum = store.Sum(evt => evt.Amount, from: start, to: end);

// Média
var avg = store.Average(evt => evt.Value, from: start, to: end);

// Mínimo e máximo
var min = store.Min(evt => evt.Score, from: start, to: end);
var max = store.Max(evt => evt.Score, from: start, to: end);

// Com filtros
var filteredSum = store.Sum(
    evt => evt.Amount, 
    filter: evt => evt.Type == "Payment",
    from: start, 
    to: end
);

Snapshots com Filtros

// Snapshot filtrado
var recentEvents = store.Snapshot(
    filter: evt => evt.Timestamp > DateTime.UtcNow.AddMinutes(-5)
);

// Snapshot por janela temporal
var snapshot = store.Snapshot(from: start, to: end);

// Snapshot com filtro e janela temporal
var filtered = store.Snapshot(
    filter: evt => evt.Amount > 100,
    from: start,
    to: end
);

Limpeza e Manutenção

// Limpar todos os eventos
store.Clear();
store.Reset(); // Alias para Clear()

// Purgar eventos antigos (requer TimestampSelector)
store.Purge(olderThan: DateTime.UtcNow.AddHours(-1));

Métricas e Observabilidade

// Estatísticas detalhadas
store.Statistics.TotalAppended        // Total de eventos adicionados
store.Statistics.TotalDiscarded       // Total de eventos descartados
store.Statistics.AppendsPerSecond     // Taxa atual de adições
store.Statistics.LastAppendTime       // Timestamp da última adição

Samples

MetricsDashboard

API web completa para coleta e consulta de métricas em tempo real:

cd .\samples\MetricsDashboard\
dotnet run

Endpoints disponíveis:

  • POST /metrics - Adicionar métrica
  • GET /metrics/sum?label=cpu_usage - Somar valores por label
  • GET /metrics/top?k=5 - Top K métricas

Veja samples/MetricsDashboard/TESTING.md para guia completo de testes.

API Completa

  • TryAppend(event) — Adiciona evento, lock-free
  • Aggregate — Agrega valores por janela temporal
  • Snapshot() — Retorna cópia imutável dos eventos
  • Count/Sum/Average/Min/Max — Agregações especializadas
  • Clear/Reset/Purge — Métodos de limpeza
  • Query — Consultas flexíveis com filtros
  • Statistics — Métricas para monitoramento

Partições

O número de partições padrão é Environment.ProcessorCount. É possível forçar a partição usando TryAppend(e, partition).

Snapshots

Snapshot() retorna uma cópia imutável aproximada do estado atual de todas as partições, ordenada do evento mais antigo para o mais novo por partição.

Performance

Projetado para alta concorrência e baixa latência. A ordem global entre partições é aproximada.

Performance Benchmarks

Value Type vs Reference Type Events

Benchmarks comparing the performance of value type events (Event struct) vs reference type events (MetricEvent class):

Operation Value Type Reference Type Improvement
Event Addition 560 ms 797 ms 42% faster
Event Iteration 35.8 ns 132.5 ns 74% faster
Event Queries 393.5 ns 1,749.1 ns 77% faster

Structure of Arrays (SoA) vs Array of Structures (AoS)

Benchmarks comparing memory layout approaches:

Operation SoA AoS Improvement
Aggregation by Key 55.2 ms 74.6 ms 26% faster
Memory Usage Lower Higher Varies

The benchmarks confirm that:

  1. Value types provide significantly better performance than reference types for both write and read operations
  2. The Structure of Arrays (SoA) approach improves cache locality and reduces memory pressure
  3. For high-throughput scenarios, the optimized EventStoreV2 implementation is recommended
// Using the optimized EventStoreV2 with value types
var store = new EventStoreV2(capacity: 1_000_000, partitions: 16);

// Adding events with zero allocations
store.Add("sensor1", 25.5, DateTime.UtcNow.Ticks);

// Fast aggregation
double average = store.Average("sensor1");

Limitações

  • Ordem global apenas aproximada entre partições
  • Capacidade fixa; eventos antigos são descartados ao exceder

Licença

MIT

Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.11 164 8/27/2025
1.0.10 169 8/26/2025
1.0.9 172 8/26/2025
1.0.8 121 8/21/2025
1.0.7 127 8/20/2025
1.0.6 122 8/20/2025
1.0.5 124 8/10/2025
1.0.2 229 8/6/2025
1.0.0 153 8/4/2025
0.1.3 27 8/2/2025
0.1.2 96 8/1/2025
0.1.1 96 8/1/2025

v1.0.1: Update project metadata and enhance README with new features and examples