Fix Kafka retry seek, bound buffers, and cut hot-path CPU/memory waste (Phases 41–44).
CI / changes (push) Successful in 17s
CI / frontend (push) Skipped
CI / backend (push) Successful in 15m10s

Stop consumers from committing past failed offsets, harden Rabbit/DataLake/gateway backpressure, dispose JsonDocument/MinIO correctly, and batch expensive DB/HTTP paths. Track progress in docs/performance.
This commit is contained in:
2026-11-30 21:32:43 +08:00
parent 1c1065938f
commit 68a2ab3204
54 changed files with 959 additions and 311 deletions
@@ -9,7 +9,8 @@ public static class DataLakeEventParser
{
public static ObservationRow ParseObservationRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
var encounterId = GetString(d, "encounterId");
var observationId = GetString(d, "observationId");
if (string.IsNullOrEmpty(observationId))
@@ -31,7 +32,8 @@ public static class DataLakeEventParser
public static AlertRow ParseAlertRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new AlertRow(
AlertId : GetString(d, "alertId"),
EncounterId : GetString(d, "encounterId"),
@@ -47,7 +49,8 @@ public static class DataLakeEventParser
public static EncounterStatusRow ParseEncounterRow(string payload, long offset, int partition)
{
var d = JsonDocument.Parse(payload).RootElement;
using var doc = JsonDocument.Parse(payload);
var d = doc.RootElement;
return new EncounterStatusRow(
EncounterId : GetString(d, "encounterId"),
PatientId : GetString(d, "patientId"),
@@ -62,7 +65,7 @@ public static class DataLakeEventParser
{
try
{
var doc = JsonDocument.Parse(payload);
using var doc = JsonDocument.Parse(payload);
var ts = topic switch
{
var t when t == topics.ObservationRecorded => GetTimestamp(doc.RootElement, "recordedAt"),
@@ -11,6 +11,13 @@ public sealed class DataLakeOptions
// Production: 300 seconds (5 minutes). Tests: 10 seconds.
public int FlushIntervalSeconds { get; init; } = 300;
/// <summary>
/// Hard cap on in-memory buffered events across all partitions. When reached,
/// consume seeks back and pauses until a flush frees space (prevents OOM when
/// MinIO is down while Kafka keeps delivering).
/// </summary>
public int MaxBufferedEvents { get; init; } = 50_000;
// MinIO bucket. The discharge summary worker from Phase 6 uses the same bucket
// under a different prefix — all VigilCare data stays in one bucket.
public string BucketName { get; init; } = "vigilcare";
@@ -1,6 +1,7 @@
using System.Text.Json;
using Confluent.Kafka;
using Microsoft.Extensions.Options;
using Minio;
using Minio.DataModel.Args;
public sealed class DataLakeWriterService : BackgroundService
@@ -8,6 +9,7 @@ public sealed class DataLakeWriterService : BackgroundService
private readonly KafkaOptions _kafkaOptions;
private readonly DataLakeOptions _opts;
private readonly MinioOptions _minioOpts;
private readonly IMinioClient _minio;
private readonly ILogger<DataLakeWriterService> _logger;
// Buffer key: identifies one Parquet file-to-be.
@@ -24,11 +26,13 @@ public sealed class DataLakeWriterService : BackgroundService
IOptions<KafkaOptions> kafkaOptions,
IOptions<DataLakeOptions> opts,
IOptions<MinioOptions> minioOpts,
IMinioClient minio,
ILogger<DataLakeWriterService> logger)
{
_kafkaOptions = kafkaOptions.Value;
_opts = opts.Value;
_minioOpts = minioOpts.Value;
_minio = minio;
_logger = logger;
}
@@ -51,8 +55,8 @@ public sealed class DataLakeWriterService : BackgroundService
});
_logger.LogInformation(
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval}",
_opts.FlushCount, _opts.FlushIntervalSeconds);
"DataLakeWriterService started. FlushCount={FlushCount} FlushIntervalSeconds={FlushInterval} MaxBufferedEvents={MaxBuffered}",
_opts.FlushCount, _opts.FlushIntervalSeconds, _opts.MaxBufferedEvents);
var lastFlush = DateTimeOffset.UtcNow;
@@ -72,7 +76,24 @@ public sealed class DataLakeWriterService : BackgroundService
}
if (result is not null)
{
var totalBefore = _buffer.Values.Sum(v => v.Count);
if (totalBefore >= _opts.MaxBufferedEvents)
{
// Consume advanced the position — seek back so we do not drop the message.
consumer.Seek(result.TopicPartitionOffset);
_logger.LogCritical(
"[DATA-LAKE] Buffer at cap {Cap} — pausing consume until flush frees space",
_opts.MaxBufferedEvents);
await FlushAsync(consumer, ct);
lastFlush = DateTimeOffset.UtcNow;
if (_buffer.Values.Sum(v => v.Count) >= _opts.MaxBufferedEvents)
await Task.Delay(5_000, ct);
continue;
}
AddToBuffer(result);
}
var totalBuffered = _buffer.Values.Sum(v => v.Count);
var shouldFlushCount = totalBuffered >= _opts.FlushCount;
@@ -245,18 +266,18 @@ public sealed class DataLakeWriterService : BackgroundService
private async Task UploadToMinioAsync(string objectKey, byte[] bytes, CancellationToken ct)
{
var client = MinioClientFactory.Build(_minioOpts);
var bucket = _opts.BucketName;
var exists = await client.BucketExistsAsync(
var exists = await _minio.BucketExistsAsync(
new BucketExistsArgs().WithBucket(bucket), ct);
if (!exists)
await client.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
await _minio.MakeBucketAsync(new MakeBucketArgs().WithBucket(bucket), ct);
await client.PutObjectAsync(new PutObjectArgs()
await using var stream = new MemoryStream(bytes);
await _minio.PutObjectAsync(new PutObjectArgs()
.WithBucket(bucket)
.WithObject(objectKey)
.WithStreamData(new MemoryStream(bytes))
.WithStreamData(stream)
.WithObjectSize(bytes.Length)
.WithContentType("application/octet-stream"),
ct);