Cookbook

Memory Management

Glueful's memory-management tooling — the memory manager, alerting, efficient iterators, object pool, chunked DB processing, lazy container — plus a note on tracing and metrics.

This guide consolidates Glueful's memory-management and observability tools into a single reference: real-time memory monitoring and alerting, memory-efficient iteration over large datasets, object pooling, chunked database processing, the lazy service container, and request tracing.

Memory Manager

The Memory Manager provides advanced memory monitoring, tracking, and management capabilities with configurable thresholds and automatic garbage collection.

Features

  • Real-time Memory Monitoring: Track current, peak, and limit usage
  • Automatic Garbage Collection: Trigger collection based on configurable thresholds
  • Memory State Tracking: Monitor allocation patterns and system health
  • Configurable Alerts: Set custom thresholds for different memory states

Basic Usage

use Glueful\Performance\MemoryManager;

// Resolve from the container (or construct with an optional logger/context)
$memoryManager = app($context, MemoryManager::class);

// Monitor memory usage (logs + runs GC when thresholds are exceeded)
$usage = $memoryManager->monitor();
echo "Current: {$usage['formatted']['current']}, Peak: {$usage['formatted']['peak']}";

// Check memory state
if ($memoryManager->isMemoryCritical()) {
    // Handle critical memory situation
    $memoryManager->forceGarbageCollection();
}

Configuration Options

Thresholds are read from configuration (defaults shown), not from the constructor:

// config/app.php → 'performance' (or the MEMORY_* environment overrides)
'performance' => [
    'memory' => [
        'monitoring' => [
            'enabled' => true,
            'alert_threshold' => 0.8,     // MEMORY_ALERT_THRESHOLD — high-usage alert at 80%
            'critical_threshold' => 0.9,  // MEMORY_CRITICAL_THRESHOLD — critical at 90%
        ],
    ],
],

Memory States

monitor() compares current usage (percentage = usage ÷ memory_limit) against the configured thresholds:

  • Normal: Usage below alert_threshold
  • High: Usage at/above alert_threshold (logged; optional GC) — see isMemoryHighUsage()
  • Critical: Usage at/above critical_threshold — see isMemoryCritical()

Advanced Features

// Inspect the active memory limit
$limit = $memoryManager->getMemoryLimit();              // bytes
$human = $memoryManager->getFormattedMemoryLimit();     // e.g. "512 MB"

// Force garbage collection
$memoryManager->forceGarbageCollection();

// Get current memory statistics (current/peak/limit/percentage + formatted values)
$stats = $memoryManager->getCurrentUsage();
print_r($stats);

// Quick threshold checks
$high     = $memoryManager->isMemoryHighUsage();
$critical = $memoryManager->isMemoryCritical();

Memory Alerting Service

MemoryAlertingService checks usage through a MemoryManager and sends throttled alerts when it crosses a threshold.

Basic Setup

use Glueful\Performance\MemoryAlertingService;
use Glueful\Performance\MemoryManager;
use Psr\Log\LoggerInterface;

$alerts = new MemoryAlertingService(
    app($context, MemoryManager::class),
    app($context, LoggerInterface::class),
    $context
);

// Check now; alerts fire through the configured channels if a threshold is crossed
$usage = $alerts->checkAndAlert('import-job', ['batch' => $batchId]);

Call checkAndAlert() at natural checkpoints in long-running work (between chunks, in a worker loop). It returns the current usage.

Configuration

The service reads app.performance.memory.alerting. The framework's config/app.php doesn't define that block, so these built-in defaults apply until you add it to your own config/app.php:

// config/app.php
'performance' => [
    'memory' => [
        'alerting' => [
            'enabled' => true,
            'cooldown' => 300,               // seconds between similar alerts
            'channels' => ['log', 'slack'],  // log | slack | email | webhook
            'log_level' => 'warning',        // critical alerts always log at error
            'notify_threshold' => 0.85,      // fraction of memory_limit
            'critical_threshold' => 0.95,
            'alert_rate_limit' => 10,        // max alerts per hour
        ],
    ],
],

Alert Channels

  • log: writes to the logger you passed in.
  • slack: posts to notifications.slack.webhook_url.
  • webhook: POSTs a JSON payload (level, message, data) to notifications.webhook.url with an X-Alert-Type: memory header.
  • email: sends to notifications.email.to (one address or a list) through the registered email notification channel, such as the one glueful/email-notification provides. Pass the $context so the service can reach the channel. With no email channel registered, it logs one warning and skips email alerts (before 1.91 it only logged that it would send).

A channel without its config logs a warning and is skipped. These notifications.* keys live in an app config file config/notifications.php (the framework ships none). resetRateLimit() clears the hourly counter.

Memory Efficient Iterators

Memory efficient iterators for processing large datasets without loading everything into memory.

StreamingIterator

Wrap any iterable, generator, or array and stream it through a bounded in-memory buffer:

use Glueful\Performance\StreamingIterator;

// Second argument is the buffer size (items held in memory at once); default 100.
$iterator = new StreamingIterator($dataSource, 1000);

foreach ($iterator as $item) {
    processItem($item);
}

Lazy database streaming

Stream a large result set row by row instead of fetching it all at once — pass an executed PDO statement to MemoryEfficientIterators::databaseResults(), which yields rows in batches:

use Glueful\Performance\MemoryEfficientIterators;

$stmt = db($context)->getPDO()->prepare('SELECT * FROM events WHERE created_at >= ?');
$stmt->execute([$since]);

// Generator — fetches `$fetchSize` rows at a time (default 100), never the whole set.
foreach (MemoryEfficientIterators::databaseResults($stmt, 500) as $row) {
    processItem($row);
}

Mapping & filtering without buffering

map() and filter() return generators, so transforms and predicates apply lazily as you iterate — no intermediate array is built:

use Glueful\Performance\MemoryEfficientIterators;

$active = MemoryEfficientIterators::filter(
    $dataSource,
    fn ($item) => $item['status'] === 'active' && $item['score'] > 50,
);

foreach ($active as $item) {
    processActiveHighScoreItem($item);
}

// Compose helpers — stream a file line by line, then map each line:
foreach (MemoryEfficientIterators::map(
    MemoryEfficientIterators::fileLineByLine('/path/to/large.csv'),
    fn ($line) => str_getcsv($line),
) as $columns) {
    // ...
}

Chunked processing

For chunk-at-a-time work (e.g. bulk inserts), processInChunks() calls your callback once per chunk:

use Glueful\Performance\MemoryEfficientIterators;

MemoryEfficientIterators::processInChunks($dataSource, function (array $chunk) {
    // $chunk holds up to the chunk size (default 1000) items
    bulkInsert($chunk);
}, chunkSize: 1000);

Memory Pool

Object storage and reuse system to reduce memory allocation overhead.

Features

  • Object Pooling: Reuse expensive objects by key
  • Bounded Size: LRU eviction removes least-recently-used entries when the pool is full
  • Statistics: Monitor pool usage and efficiency

Basic Usage

MemoryPool is a bounded, keyed object store for reusing expensive-to-build objects within a process. Construct it with a maximum size, then add/get/has/remove objects by key:

use Glueful\Performance\MemoryPool;

$pool = new MemoryPool(maxSize: 100);

// Store an object under a key (evicts the least-recently-used entry if the pool is full)
$pool->add('report:' . $id, $expensiveReport);

// Reuse it later instead of rebuilding
if ($pool->has('report:' . $id)) {
    $report = $pool->get('report:' . $id);
}

$pool->remove('report:' . $id);   // drop one entry
$pool->clear();                    // drop everything

When the pool reaches maxSize, the least-recently-used entries are evicted to make room, so it bounds memory automatically.

Pool statistics

$stats = $pool->getStats();   // array of pool-usage metrics (size, capacity, hit/miss counters)
$keys  = $pool->getKeys();    // the keys currently held

Memory Monitor Command

CLI tool for monitoring and analyzing memory usage patterns.

Basic Usage

# Real-time memory monitoring
php glueful system:memory

# Monitor with custom interval
php glueful system:memory --interval=5

# Monitor an external command's memory usage
php glueful system:memory "php glueful queue:work --stop-when-empty"

# Log metrics to a CSV file
php glueful system:memory --log --csv-file=memory_report.csv

Command Options

# Monitoring options
--interval=N, -i    # Check interval in seconds (default: 1)
--duration=N, -d    # Monitor for N seconds (0 = unlimited, default)
--threshold=N, -t   # Alert threshold in MB (default: 128)
--watch, -w         # Watch mode with real-time updates

# Output options
--format=FORMAT, -f # Output format: table, json, plain (default: table)
--log, -l           # Log memory usage to a CSV file
--csv-file=FILE, -c # CSV file path (default: memory-usage.csv)

# Analysis options
--analysis, -a      # Perform memory analysis and leak detection
--profile, -p       # Enable detailed memory profiling
--trends            # Show memory usage trends and statistics
--summary, -s       # Show memory summary and recommendations
--alert-script=PATH # Script to run when the threshold is exceeded

Real-time Monitoring

# Display live memory usage
php glueful system:memory --interval=1 --format=table

┌─────────────────┬──────────────┬─────────────┬─────────────┐
│ Time            │ Current (MB) │ Peak (MB)   │ Limit (MB)  │
├─────────────────┼──────────────┼─────────────┼─────────────┤
│ 2023-10-15 14:30│ 245.7       │ 267.3       │ 512.0       │
│ 2023-10-15 14:31│ 248.2       │ 267.3       │ 512.0       │
│ 2023-10-15 14:32│ 251.8       │ 267.3       │ 512.0       │
└─────────────────┴──────────────┴─────────────┴─────────────┘

Memory Analysis

# Run for a fixed duration and log metrics to CSV
php glueful system:memory --duration=300 --log --csv-file=analysis.csv

# Perform analysis and leak detection
php glueful system:memory --analysis --summary

Memory Usage Analysis Report
============================
Average Usage: 245.7 MB
Peak Usage: 312.4 MB
Memory Efficiency: 87.3%
Potential Issues: 2 memory spikes detected

Integration with Monitoring Systems

# Run an external alert script when the threshold (in MB) is exceeded
php glueful system:memory \
    --threshold=256 \
    --alert-script=/usr/local/bin/notify-ops.sh

Chunked Database Processor

Process large database result sets in memory-efficient chunks.

Features

  • Chunked Processing: Process large datasets without memory issues
  • Configurable Chunk Sizes: Set a default chunk size on the constructor, or override per call
  • Multiple Sources: Process a raw SELECT query or iterate a table by id, over a Glueful Connection, PDO or mysqli

Basic Usage

The constructor takes a Connection|PDO|mysqli and an optional default chunk size. Since 1.91 you can pass the Glueful Connection directly (db($context)): table chunking then goes through the query builder. Before, only a PDO or mysqli handle worked. The per-call chunk size is the last argument of each processing method, overriding the default.

use Glueful\Performance\ChunkedDatabaseProcessor;

// Second argument is the default chunk size (default 1000)
$processor = new ChunkedDatabaseProcessor(db($context), 1000);

// Process a SELECT query in chunks. The processor callback receives each chunk
// (an array of rows) and its return values are collected into the result array.
$results = $processor->processSelectQuery(
    'SELECT * FROM large_table WHERE active = ?',
    function (array $rows) {
        foreach ($rows as $row) {
            updateUserRecord($row);
        }
        return count($rows);
    },
    [1],   // query parameters
    500    // chunk size for this call (overrides the default)
);

Processing a Table by Id

processTableInChunks() iterates a table in id-ordered chunks, applying optional equality conditions. Each chunk is passed to the processor callback.

$results = $processor->processTableInChunks(
    'users',
    function (array $rows) {
        foreach ($rows as $user) {
            sendNotification($user);
        }
        return count($rows);
    },
    'id',                    // id column to paginate on
    ['status' => 'active'],  // equality conditions
    500                      // chunk size (overrides the default)
);

Chunk Size

The chunk size is the only tunable. Set a default on the constructor and override it per call via the last argument of processSelectQuery() / processTableInChunks():

// Default of 2000 rows per chunk for every call on this instance
$processor = new ChunkedDatabaseProcessor(db($context), 2000);

// Override to 250 for a single, heavier-per-row job
$processor->processSelectQuery($query, $callback, $params, 250);

Lazy Container

Deferred object creation container for improved memory efficiency and performance. It exposes just two methods: register() to bind a factory closure under an id, and get() to resolve it. The factory runs the first time the id is requested, and the resulting instance is cached and returned on every subsequent get().

Basic Usage

use Glueful\Performance\LazyContainer;

$container = new LazyContainer();

// Register factory closures
$container->register('database', function () use ($config) {
    return new DatabaseConnection($config);
});

$container->register('userService', function () use ($container) {
    return new UserService($container->get('database'));
});

// Objects are created only when first accessed, then cached
$userService = $container->get('userService'); // 'database' is built here, on first use
$sameService = $container->get('userService'); // returns the cached instance

Notes

  • There is no auto-wiring, aliasing, tagging, or statistics API — the container simply instantiates each registered factory lazily on the first get() and memoizes the result.
  • Express dependencies by resolving them from the container inside the factory closure (as shown with $container->get('database') above).

Best Practices

Memory Management Guidelines

  1. Monitor Continuously: Use real-time monitoring for production systems
  2. Set Appropriate Thresholds: Configure warnings before critical situations
  3. Use Object Pooling: Reuse expensive objects when possible
  4. Process in Chunks: Handle large datasets with chunked processing
  5. Lazy Load Resources: Create objects only when needed

Performance Optimization

  1. Choose Right Tools: Select appropriate iterator for your use case
  2. Configure Limits: Set memory limits for all processing tasks
  3. Enable Alerting: Get notified before problems occur
  4. Track Metrics: Monitor memory patterns and trends
  5. Regular Cleanup: Implement automated cleanup processes

Common Patterns

// Combine multiple tools for optimal performance
$container = new LazyContainer();
$pool = new MemoryPool(maxSize: 10);
$processor = new ChunkedDatabaseProcessor(db($context), 1000);

// Reuse an expensive-to-build worker across chunks via the keyed pool
$processor->processSelectQuery($query, function (array $rows) use ($pool) {
    if (!$pool->has('worker')) {
        $pool->add('worker', new BatchWorker());
    }

    $worker = $pool->get('worker');
    $worker->processBatch($rows);

    return count($rows);
}, $params);

This comprehensive memory management system provides all the tools needed to build memory-efficient, scalable applications with Glueful.

Tracing and Metrics

Request tracing goes through Glueful\Observability\Tracing\TracerInterface (startSpan($name, $attrs) returns a SpanBuilderInterface with setAttribute(), setParent() and startSpan(); the started SpanInterface has setAttribute() and end()). The container binds the no-op NoopTracer by default, so spans cost nothing until you bind a real tracer (for example an OpenTelemetry adapter) to TracerInterface in your provider. The tracing middleware also follows TRACING_ENABLED (observability.tracing.enabled, default false): while it's off, the middleware passes requests through without opening spans, so set it to true when you bind a real tracer. observability.tracing.enabled is the only tracing key; the binding decides which tracer runs. Since 1.91, TRACING_DRIVER, TRACING_SERVICE_NAME and TRACING_SERVICE_VERSION (and the driver, drivers, service_name and service_version keys) are removed, so delete them from .env and any app copy of config/observability.php.

Two middleware aliases cover request-level observability:

  • tracing (with TRACING_ENABLED=true) opens an http.request span per request with the method, route template, user agent, client IP, request id and status code.
  • metrics records the request through ApiMetricsService (stored in the api_metrics tables, which core migrations always install).
$router->group(['middleware' => ['tracing', 'metrics']], function ($router) {
    $router->get('/reports', [ReportController::class, 'index']);
});

Custom spans use the same interface:

use Glueful\Observability\Tracing\TracerInterface;

$span = app($context, TracerInterface::class)
    ->startSpan('reports.build', ['report.type' => $type])
    ->startSpan();

try {
    $report = $builder->build($type);
    $span->setAttribute('report.rows', count($report));
} finally {
    $span->end();
}