
Mi API se cayó en producción. 500.000 registros en una base de datos, un List
Pasé dos horas mirando los logs antes de entender qué había pasado. La solución tardó diez minutos. Esto es lo que aprendí — y cómo te ahorrará el mismo quebradero de cabeza a ti.
El problema que vamos a resolver
Lo sé, lo sé. Has escrito esto cien veces:
// ❌ El problema: 1 millón de registros en memoria
public async Task<List<LogEntry>> GetAllLogsAsync()
{
return await _context.LogEntries.ToListAsync(); // ¡Bum! Explosión de memoria
}
¿Para un puñado de registros? Sin problema. Pero el día que tu conjunto de datos crezca más allá de lo que cabe en RAM, ese inocente ToListAsync() se convierte en una bomba de relojería.
¿Qué es IAsyncEnumerable?
Introducido en C# 8.0 (.NET Core 3.0), IAsyncEnumerable<T> te permite transmitir datos de forma asíncrona (streaming) — procesando elementos uno a uno a medida que llegan, sin mantener nunca la colección completa en memoria. Es como leer un libro página a página en lugar de fotocopiarlo entero antes de empezar.
// ✅ La solución: streaming a medida que llegan los datos
public IAsyncEnumerable<LogEntry> StreamLogsAsync()
{
return _context.LogEntries.AsAsyncEnumerable(); // Eficiente en memoria
}
Patrones listos para producción
Estos son los cuatro patrones a los que recurro más a menudo. No es teoría — son cosas que he llevado a producción de verdad.
Patrón 1: Streaming con Entity Framework Core
Por aquí empieza la mayoría, y con razón. Si usas EF Core y tienes una tabla que crece con el tiempo, antes o después necesitarás este patrón.
public class LogRepository
{
private readonly AppDbContext _context;
public LogRepository(AppDbContext context)
{
_context = context;
}
/// <summary>
/// Transmite (streaming) los logs que cumplen el criterio sin cargarlos todos en memoria.
/// ADVERTENCIA: NO usar con OrderBy/Limit sin pensarlo bien.
/// </summary>
public async IAsyncEnumerable<LogEntry> StreamLogsAsync(
DateTime from,
DateTime to,
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var log in _context.LogEntries
.Where(l => l.Timestamp >= from && l.Timestamp <= to)
.AsAsyncEnumerable()
.WithCancellation(ct))
{
yield return log;
}
}
/// <summary>
/// Divide en lotes (chunks) las exportaciones grandes para evitar timeouts de conexión.
/// </summary>
public async IAsyncEnumerable<IReadOnlyList<LogEntry>> StreamBatchedLogsAsync(
int batchSize = 1000,
[EnumeratorCancellation] CancellationToken ct = default)
{
var query = _context.LogEntries
.OrderBy(l => l.Id)
.AsAsyncEnumerable();
var batch = new List<LogEntry>(batchSize);
await foreach (var log in query.WithCancellation(ct))
{
batch.Add(log);
if (batch.Count >= batchSize)
{
yield return batch.ToList();
batch.Clear();
}
}
// No olvides el lote parcial
if (batch.Count > 0)
{
yield return batch;
}
}
}
Patrón 2: Streaming con HttpClient y JSON
Las APIs de terceros que devuelven miles de registros en una sola respuesta son sorprendentemente comunes. Sin streaming, almacenas en búfer toda la respuesta antes de deserializar un solo objeto. HttpCompletionOption.ResponseHeadersRead es la línea que lo cambia todo aquí — no la olvides.
public class StreamingApiClient
{
private readonly HttpClient _httpClient;
private readonly JsonSerializerOptions _jsonOptions;
public StreamingApiClient(HttpClient httpClient)
{
_httpClient = httpClient;
_jsonOptions = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
DefaultBufferSize = 4096 // Ajusta esto según el tamaño de tu payload
};
}
/// <summary>
/// Transmite elementos desde un endpoint NDJSON.
/// Cada línea es un objeto JSON independiente.
/// </summary>
public async IAsyncEnumerable<T> StreamFromNdJsonAsync<T>(
string url,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var response = await _httpClient.GetAsync(
url,
HttpCompletionOption.ResponseHeadersRead, // Crítico: streaming, no buffering
ct);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(ct);
using var reader = new StreamReader(stream, Encoding.UTF8);
string? line;
while ((line = await reader.ReadLineAsync(ct)) != null)
{
if (string.IsNullOrWhiteSpace(line))
continue;
// Deserializa cada línea de forma independiente
var item = JsonSerializer.Deserialize<T>(line, _jsonOptions);
if (item != null)
yield return item;
}
}
/// <summary>
/// Transmite usando la deserialización asíncrona integrada de System.Text.Json.
/// Requiere formato de array JSON: [{}, {}, {}]
/// </summary>
public async IAsyncEnumerable<T> StreamJsonArrayAsync<T>(
string url,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var response = await _httpClient.GetAsync(
url,
HttpCompletionOption.ResponseHeadersRead,
ct);
response.EnsureSuccessStatusCode();
await using var stream = await response.Content.ReadAsStreamAsync(ct);
await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<T>(
stream,
_jsonOptions,
ct))
{
if (item != null)
yield return item;
}
}
}
Patrón 3: Pipeline de procesamiento de ficheros
Importaciones de CSV, análisis de logs, migraciones de datos — cualquier cosa que lea un fichero línea a línea y haga algo con cada fila. La idea clave aquí es que puedes encadenar varios métodos IAsyncEnumerable<T> en un pipeline donde el consumo de memoria se mantiene plano sin importar el tamaño del fichero.
public class LogFileProcessor
{
/// <summary>
/// Lee, transforma y escribe logs en un pipeline de streaming.
/// El consumo de memoria se mantiene constante sin importar el tamaño del fichero.
/// </summary>
public async IAsyncEnumerable<ProcessedLog> ProcessLogFileAsync(
string filePath,
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var rawLog in ReadLinesAsync(filePath, ct))
{
// Transforma al vuelo - sin acumulación de memoria
if (TryParseLog(rawLog, out var parsed))
{
var enriched = await EnrichLogAsync(parsed, ct);
yield return enriched;
}
}
}
private static async IAsyncEnumerable<string> ReadLinesAsync(
string path,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var reader = new StreamReader(path, Encoding.UTF8);
string? line;
while ((line = await reader.ReadLineAsync(ct)) != null)
{
yield return line;
}
}
private static bool TryParseLog(string raw, out ParsedLog parsed)
{
// Tu lógica de parseo aquí
parsed = default!;
return true;
}
private static async Task<ProcessedLog> EnrichLogAsync(
ParsedLog log,
CancellationToken ct)
{
// Enriquecimiento asíncrono (p. ej., consultar datos de usuario)
await Task.Delay(1, ct); // Simula trabajo asíncrono
return new ProcessedLog(log);
}
}
public record ParsedLog(string Timestamp, string Level, string Message);
public record ProcessedLog(ParsedLog Original);
Patrón 4: Acción de controlador con respuesta en streaming
ASP.NET Core gestiona de forma nativa los tipos de retorno IAsyncEnumerable<T> — los serializa como NDJSON y empieza a enviar datos al cliente inmediatamente. El cliente no espera el conjunto de datos completo; empieza a recibir registros en cuanto el primero está listo.
[ApiController]
[Route("api/[controller]")]
public class ReportsController : ControllerBase
{
private readonly IReportService _reportService;
public ReportsController(IReportService reportService)
{
_reportService = reportService;
}
/// <summary>
/// Transmite datos CSV directamente al cliente.
/// El cliente empieza a recibir datos inmediatamente, sin buffering en el servidor.
/// </summary>
[HttpGet("export")]
public IAsyncEnumerable<ReportRow> ExportData(
[FromQuery] DateTime from,
[FromQuery] DateTime to,
CancellationToken ct)
{
// ASP.NET Core serializa automáticamente IAsyncEnumerable como NDJSON
// o usa formato personalizado para CSV
return _reportService.StreamReportAsync(from, to, ct);
}
/// <summary>
/// Streaming personalizado para Server-Sent Events (SSE).
/// </summary>
[HttpGet("live-events")]
public async IAsyncEnumerable<ServerSentEvent> GetLiveEvents(
[EnumeratorCancellation] CancellationToken ct)
{
await foreach (var evt in _reportService.SubscribeToEventsAsync(ct))
{
yield return new ServerSentEvent
{
Id = evt.Id,
Event = evt.Type,
Data = JsonSerializer.Serialize(evt.Payload)
};
}
}
}
public record ReportRow(string Id, string Name, decimal Value);
public record ServerSentEvent(string Id, string Event, string Data);
Antes vs. después: comparativa de rendimiento
Vamos a concretarlo. Mismos datos, misma operación, dos enfoques.
El enfoque antiguo: List (antes)
public async Task<List<LargeRecord>> ProcessAllRecordsAsync()
{
// Memoria: O(n) - crece con el tamaño del dataset
// Tiempo hasta el primer resultado: O(n) - hay que esperar a que termine todo
var allRecords = await _repository.GetAllAsync();
var processed = new List<LargeRecord>();
foreach (var record in allRecords)
{
processed.Add(await ProcessAsync(record));
}
return processed;
}
// Uso - aquí se dispara el consumo de memoria
var results = await ProcessAllRecordsAsync();
foreach (var item in results)
{
await WriteToDiskAsync(item);
}
1M registros de 100 KB cada uno — lo que pasa en realidad:
- Memoria pico: ~95 GB (sí, gigabytes)
- Tiempo hasta el primer resultado: 45 segundos de espera
- Resultado: OutOfMemoryException — tu servidor se rinde antes que tú
El nuevo enfoque: IAsyncEnumerable (después)
public async IAsyncEnumerable<LargeRecord> ProcessAllRecordsAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
// Memoria: O(1) - constante sin importar el tamaño del dataset
// Tiempo hasta el primer resultado: O(1) - streaming inmediato
await foreach (var record in _repository.StreamAllAsync(ct))
{
yield return await ProcessAsync(record);
}
}
// Uso - huella de memoria constante
await foreach (var item in ProcessAllRecordsAsync().WithCancellation(ct))
{
await WriteToDiskAsync(item);
}
Los mismos 1M registros — una historia completamente distinta:
- Memoria pico: ~150 MB (constante, sin importar el tamaño del dataset)
- Tiempo hasta el primer resultado: 50 ms — el cliente empieza a recibir datos casi al instante
- Resultado: Streaming fluido, el servidor se mantiene saludable
Resultados con BenchmarkDotNet

Errores comunes y cómo solucionarlos
He cometido todos y cada uno de estos errores. Tú no tienes por qué.
Error 1: Olvidar el CancellationToken
// ❌ Mal: no hay forma de cancelar a mitad del streaming
public async IAsyncEnumerable<Item> GetItemsAsync()
{
await foreach (var item in _source.GetAsync())
{
yield return item; // ¡Esto no se puede cancelar!
}
}
// ✅ Bien: incluye siempre soporte de cancelación
public async IAsyncEnumerable<Item> GetItemsAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var item in _source.GetAsync().WithCancellation(ct))
{
yield return item;
}
}
Error 2: Hacer buffering con ToListAsync()
// ❌ Mal: acabas de anular el propósito de todo esto
public async Task<List<Item>> GetItemsAsync() // Devuelve List<T>, no IAsyncEnumerable
{
var items = new List<Item>();
await foreach (var item in _source.GetAsync())
{
items.Add(item);
}
return items;
}
// ✅ Bien: devuelve IAsyncEnumerable<T> directamente
public IAsyncEnumerable<Item> GetItemsAsync(CancellationToken ct)
{
return _source.GetAsync(); // Pásalo en streaming
}
Error 3: Liberar recursos demasiado pronto
// ❌ Mal: el reader se libera antes de que termine el streaming
public async IAsyncEnumerable<string> ReadFileAsync(string path)
{
using var reader = new StreamReader(path); // ¡Se libera en el primer yield!
while (await reader.ReadLineAsync() is { } line)
{
yield return line; // el reader ya está liberado
}
}
// ✅ Bien: mantén el scope vivo
public async IAsyncEnumerable<string> ReadFileAsync(
string path,
[EnumeratorCancellation] CancellationToken ct = default)
{
using var reader = new StreamReader(path);
try
{
while (await reader.ReadLineAsync(ct) is { } line)
{
yield return line;
}
}
finally
{
// el reader se libera cuando la iteración termina o se interrumpe
}
}
Error 4: No configurar el ciclo de vida del DbContext
// ❌ Mal: el DbContext con ámbito scoped se libera a mitad del streaming en ASP.NET Core
[HttpGet("stream")]
public async IAsyncEnumerable<Order> GetOrders()
{
var db = _serviceProvider.GetRequiredService<OrderDbContext>();
// ¡db se liberará en cuanto el método de acción retorne!
await foreach (var order in db.Orders.AsAsyncEnumerable())
{
yield return order; // DbContext liberado aquí
}
}
// ✅ Bien: usa el patrón factory para streaming
public class StreamingOrderService
{
private readonly IDbContextFactory<OrderDbContext> _contextFactory;
public async IAsyncEnumerable<Order> StreamOrdersAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await using var db = await _contextFactory.CreateDbContextAsync(ct);
await foreach (var order in db.Orders.AsAsyncEnumerable().WithCancellation(ct))
{
yield return order;
}
// DbContext liberado correctamente cuando la iteración termina
}
}
Error 5: Ignorar los timeouts de transacción
// ❌ Mal: una consulta de larga duración puede agotar el timeout
public async IAsyncEnumerable<Item> GetItemsAsync()
{
await foreach (var item in _context.Items.AsAsyncEnumerable())
{
yield return item; // Conexión abierta indefinidamente
}
}
// ✅ Bien: establece un timeout de comando explícito
public async IAsyncEnumerable<Item> GetItemsAsync(CancellationToken ct)
{
_context.Database.SetCommandTimeout(TimeSpan.FromMinutes(5));
await foreach (var item in _context.Items.AsAsyncEnumerable().WithCancellation(ct))
{
yield return item;
}
}
Buenas prácticas
Unas pocas reglas que ahora sigo sin pensar.
1. Acepta siempre un CancellationToken
public async IAsyncEnumerable<T> StreamAsync(
[EnumeratorCancellation] CancellationToken ct = default)
{
await foreach (var item in _source.WithCancellation(ct))
{
ct.ThrowIfCancellationRequested(); // Opcional: comprobar entre operaciones
yield return await TransformAsync(item, ct);
}
}
2. Usa WithCancellation en el código que llama
await foreach (var item in service.StreamAsync().WithCancellation(ct))
{
// Propagación correcta de la cancelación
}
3. Configura el tamaño del búfer JSON para HttpClient
var options = new JsonSerializerOptions
{
DefaultBufferSize = 8192 // Ajusta según el tamaño medio del payload
};
await foreach (var item in JsonSerializer.DeserializeAsyncEnumerable<T>(
stream, options, ct))
{
// Uso óptimo de memoria
}
4. Añade contrapresión (backpressure) con ConfigureAwait
await foreach (var item in source.ConfigureAwait(false))
{
// false reduce los cambios de contexto en escenarios de alto throughput
await SlowOperationAsync(item).ConfigureAwait(false);
}
5. Usa IAsyncDisposable para liberar recursos
public async IAsyncEnumerable<byte[]> StreamFileChunksAsync(
string path,
int chunkSize = 8192,
[EnumeratorCancellation] CancellationToken ct = default)
{
await using var fs = new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: chunkSize,
useAsync: true);
var buffer = new byte[chunkSize];
int bytesRead;
while ((bytesRead = await fs.ReadAsync(buffer, ct)) > 0)
{
yield return buffer.AsSpan(0, bytesRead).ToArray();
}
}
6. Agrupa en lotes cuando los elementos individuales son demasiado pequeños
public async IAsyncEnumerable<IReadOnlyList<T>> StreamBatchesAsync<T>(
int batchSize = 100,
[EnumeratorCancellation] CancellationToken ct = default)
where T : class
{
var batch = new List<T>(batchSize);
await foreach (var item in _context.Set<T>().AsAsyncEnumerable().WithCancellation(ct))
{
batch.Add(item);
if (batch.Count >= batchSize)
{
yield return batch;
batch = new List<T>(batchSize);
}
}
if (batch.Count > 0)
{
yield return batch;
}
}
Conclusión
El cambio mental es sencillo en cuanto hace clic:
- Antes: Cargar todo → Procesar todo → Devolver todo
- Después: Transmitir un elemento → Procesarlo → Pasar al siguiente
Y ya está. Sin magia, sin configuración compleja. Solo una forma distinta de pensar sobre el flujo de datos.
Recurre a IAsyncEnumerable
- ✅ Exportas registros de base de datos por miles
- ✅ Procesas ficheros grandes (CSV, logs, volcados JSON)
- ✅ Consumes una API de streaming
- ✅ La memoria es una preocupación real en tu servidor
Quédate con List
- ❌ Tu conjunto de datos es pequeño (menos de ~1.000 elementos) — el overhead no compensa
- ❌ Necesitas acceso aleatorio o múltiples iteraciones
- ❌ Estás encadenando operaciones LINQ complejas que no soportan streaming
La reducción del 95% de memoria que conseguí no era teórica. Fue la diferencia entre un servicio que se caía bajo carga y uno que gestionaba los mismos datos sin inmutarse. Empieza por tus consultas de EF Core y tus clientes de API — ahí es donde notarás el impacto de inmediato.

