eBPF Runtime Security and Observability Explained
Engineering kernel-level visibility, real-time threat detection, programmable security enforcement and high-performance observability across modern Linux and Kubernetes infrastructure.
Conceptual architecture showing eBPF loading, kernel attachment, event processing, policy state and userspace telemetry. The central processor is a visual abstraction, not dedicated eBPF hardware.
Understanding the Infrastructure Beneath the Application
Modern applications execute across increasingly complex environments composed of containers, microservices, virtual machines, distributed databases, service meshes and cloud-native infrastructure.
Although these environments provide enormous flexibility, they introduce a fundamental engineering challenge: understanding what is actually happening beneath the application layer.
An application may report that a request has failed. A monitoring platform may identify increasing latency. A security platform may detect suspicious behaviour. However, these observations do not necessarily explain which kernel operation, process, network connection or resource constraint caused the underlying event.
The Linux kernel is responsible for coordinating many of these operations. Process scheduling, memory management, filesystem access, network communication and security decisions all involve kernel functionality.
eBPF provides a programmable mechanism for observing and, at supported attachment points, influencing these operations directly within the operating system.
Rather than treating infrastructure as an opaque execution environment, engineers can build a more detailed picture of how applications interact with the operating system and how individual runtime events contribute to infrastructure behaviour.
Observing an application from the outside is different from observing the operating system activity generated by that application. eBPF provides access to selected execution points where this activity can be measured, correlated and, where supported, controlled.
Networking, Security and Observability
eBPF is not a single monitoring application or security product. It is a programmable technology used by different infrastructure platforms to implement specialised capabilities.
Programmable Networking
Process packets at supported network hooks, implement forwarding decisions, collect flow information, accelerate selected networking functions and enforce network policies.
Runtime Security
Observe process execution, file access, network connections and other security-relevant events. Apply supported enforcement mechanisms according to configured security policies.
Deep Observability
Measure system call latency, CPU scheduling, network behaviour, application execution and resource utilisation using selected kernel and userspace instrumentation points.
Why eBPF Changes Infrastructure Observability
Traditional observability frequently depends on application instrumentation, log generation, operating system counters and external network monitoring systems.
These mechanisms remain essential. However, they expose different perspectives and may leave gaps between application behaviour and underlying operating system activity.
eBPF can complement existing observability by attaching specialised programs to selected kernel or userspace execution points. These programs can collect measurements, aggregate information and emit structured events.
| Observation method | Primary visibility | Engineering limitation |
|---|---|---|
| Application logs | Application-defined events and errors | Dependent on what the application records |
| Application tracing | Request journeys and application context | May require instrumentation and context propagation |
| System metrics | CPU, memory, disk and network counters | Aggregated measurements may hide individual events |
| Packet capture | Network traffic at a capture point | Limited application and process context |
| eBPF instrumentation | Selected kernel and userspace execution events | Hook availability, privileges, overhead and event loss |
eBPF does not automatically replace logs, metrics, distributed tracing or application instrumentation. Effective production observability combines these perspectives and correlates their evidence.
From eBPF Source Code to Runtime Intelligence
An eBPF program is typically compiled into BPF instructions and loaded through a userspace component. The kernel verifier evaluates the program against safety constraints before allowing it to execute.
Accepted programs may be JIT-compiled into native machine instructions on supported systems. They can then be attached to compatible execution points and invoked when relevant events occur.
The eBPF Verifier
Evaluates program behaviour, pointer types, memory access, helper usage and control flow. Verification reduces risks associated with executing programmable logic inside the kernel, but does not establish that a security policy is logically correct.
JIT Compilation
Translates verified BPF instructions into native machine instructions where supported and enabled. This can reduce execution overhead, although the total cost depends on program complexity and event frequency.
eBPF Maps
Kernel-managed data structures used for configuration, counters, lookup tables and shared state. Supported map types provide different memory, concurrency and access characteristics.
Event Delivery
Ring buffers and other supported mechanisms allow selected events to be delivered to userspace for enrichment, analysis and export. Capacity limits and consumer performance can affect event delivery.
Understanding What Happens After Deployment
Infrastructure security is not limited to scanning container images or evaluating configuration before an application is deployed.
Runtime security focuses on the behaviour of applications, processes and infrastructure while workloads are actively executing.
A container may have been deployed from an approved image, yet subsequently exhibit unexpected process execution, unusual file access or unauthorised network communication. Runtime evidence helps engineers identify and investigate these changes.
Security-relevant events can be collected at appropriate instrumentation points and correlated with workload context. Observation alone does not imply enforcement.
Process Intelligence
Identify executed programs, parent-child process relationships and unexpected execution patterns.
File Intelligence
Observe selected file operations and correlate them with process identity and security policy.
Network Intelligence
Associate supported network events with workload context and investigate unexpected communication.
Observation Is Not the Same as Enforcement
One of the most important distinctions in eBPF security engineering is the difference between collecting evidence and controlling an operation.
Observation
A tracing program records an event and exports relevant information. A userspace security agent evaluates that evidence and may generate an alert. The original operation may already have completed.
Enforcement
A program attached to a supported enforcement hook evaluates a policy and returns a decision that can deny, drop or otherwise influence the operation according to the hook's semantics.
For example, a BPF LSM program can participate in supported Linux Security Module decisions, while an XDP program can return packet-processing actions such as XDP_DROP or XDP_PASS.
These mechanisms operate in different contexts and have different capabilities. A generic tracepoint program cannot automatically block every operation it observes.
Engineers must understand which attachment point provides visibility, which supports enforcement, when a decision occurs and what happens when the security agent or event pipeline fails.
From Kernel Technology to Production Platforms
The eBPF ecosystem includes networking platforms, security engines, observability tools and development frameworks.
Each uses different program types, attachment mechanisms and userspace components to solve specific infrastructure problems.
| Technology | Primary engineering role | Representative capability |
|---|---|---|
| Cilium | Cloud-native networking and network security | eBPF-based datapath, service handling and policy |
| Hubble | Network observability | Flow visibility and workload communication context |
| Tetragon | Runtime security observability and enforcement | Process-aware events and supported tracing policies |
| Falco | Runtime threat detection | Rule-based detection using supported event sources |
| bpftrace | Dynamic tracing | System behaviour and performance investigation |
| libbpf | BPF application development | Program loading, attachment and CO-RE support |
| bpftool | Kernel BPF inspection | Inspect programs, maps, links and capabilities |
| BCC | BPF-based tracing and tooling | Performance analysis and instrumentation tools |
In Kubernetes environments, kernel-level events can be enriched with container identity, namespaces, cgroups, pod metadata and other contextual information.
This enrichment allows engineers to investigate operating system activity in the context of distributed applications rather than examining isolated process identifiers alone.
Inspecting the eBPF Environment
Before deploying an eBPF-based security or observability platform, engineers should establish which kernel capabilities are available and which BPF objects are active.
$ uname -r $ sudo bpftool feature probe $ sudo bpftool prog show $ sudo bpftool map show $ sudo bpftool link show $ sudo bpftrace -l 'tracepoint:syscalls:*'
| Command | Engineering purpose |
|---|---|
| uname -r | Identify the running Linux kernel release. |
| bpftool feature probe | Inspect available BPF features and program types. |
| bpftool prog show | Inspect loaded BPF programs visible to the caller. |
| bpftool map show | Inspect available BPF map objects. |
| bpftool link show | Inspect BPF link objects where used. |
| bpftrace -l | Discover available matching instrumentation probes. |
These commands require the relevant tools to be installed. Available results depend on kernel configuration, permissions, security restrictions and the attachment mechanisms used by the system.
Investigating an Unexpected Container Connection
Consider a Kubernetes application that normally communicates only with an internal database and a small number of approved services.
A security monitoring system identifies an unexpected outbound connection. Network flow information establishes that communication occurred, but does not by itself explain which process initiated the connection.
By correlating process execution events, connection events and Kubernetes metadata, engineers can construct a more useful investigation timeline.
The expected application workload is running inside the payments namespace.
Process execution telemetry records a child process outside the expected application execution pattern.
Network instrumentation associates an unexpected connection attempt with the observed process.
The security agent correlates process, workload and network evidence and generates an investigation alert.
Engineers examine process ancestry, application changes, destination policy and supporting infrastructure evidence.
Unexpected runtime activity is not automatically proof of compromise. Security engineers must validate workload behaviour, policy expectations and supporting evidence before determining the cause and appropriate response.
Engineering eBPF for Performance and Reliability
Executing specialised programs close to the source of infrastructure events can reduce unnecessary data movement and enable efficient event aggregation.
However, eBPF instrumentation is not free. Every executed program consumes resources, and high-frequency instrumentation can introduce measurable overhead.
CPU Overhead
Evaluate program execution cost, event frequency and the cumulative impact of multiple attached programs.
Memory Consumption
Account for map capacity, per-CPU data structures, ring buffers and userspace event processing.
Event Loss
Monitor failed event reservations, buffer saturation and consumer processing delays.
Kernel Compatibility
Validate program types, helpers, BTF availability, configuration and distribution-specific kernel support.
Privilege Management
Restrict program loading and sensitive telemetry access using appropriate capabilities and security controls.
Telemetry Governance
Limit unnecessary collection of sensitive process arguments, file information and application data.
What This Engineering Guide Will Teach
Throughout this guide, we will move from the architectural foundations of eBPF to practical runtime security, observability and production troubleshooting.
Making Infrastructure Behaviour Visible
The significance of eBPF extends beyond individual networking or security products. It provides a programmable foundation for understanding selected operating system events at their source.
By combining kernel instrumentation, workload context, security policy and structured telemetry, engineers can investigate infrastructure behaviour with greater precision.
The objective is not simply to collect more information. It is to collect the right evidence, understand its limitations and translate that evidence into reliable engineering decisions.
Observe the event. Understand the execution context. Correlate the evidence. Engineer the appropriate response.
Inside the Programmable Linux Kernel
Explore the architecture behind eBPF, programmable networking, kernel-level observability, runtime security and production cloud-native infrastructure.
Discover the programmable kernel, its engineering foundations and the architecture behind modern cloud-native visibility.
Move from kernel architecture and theoretical foundations towards practical security engineering, infrastructure observability and evidence-driven troubleshooting.
Understanding eBPF Architecture
Exploring the architectural principles that enable verified, event-driven programs to extend selected Linux kernel capabilities without requiring conventional kernel module development.
Conceptual eBPF execution architecture. Loading and verification occur before attachment. Runtime events invoke compatible attached programs, which may use maps and export telemetry. The execution chamber represents software, not dedicated hardware.
1. What Is eBPF?
eBPF is a programmable execution technology integrated into the Linux kernel that enables specialised programs to execute at supported attachment points.
These programs can inspect selected execution contexts, perform calculations, maintain state, collect measurements and return decisions appropriate to their program type.
The technology originated from the Berkeley Packet Filter, which was designed to support efficient packet filtering. Modern eBPF extends the programmable model far beyond packet capture.
Today, eBPF is used to implement networking datapaths, security monitoring, runtime policy enforcement, performance profiling and infrastructure observability.
Instruction Architecture
A defined instruction set and execution model provide the foundation for programmable BPF logic.
Event-Driven Execution
Programs execute when compatible attachment points are triggered, rather than operating as independent background processes.
Constrained Execution
Verification, program types, helper restrictions and kernel access controls constrain what loaded programs can perform.
eBPF brings programmable logic to selected operating system execution points. It does not provide unrestricted access to arbitrary kernel memory or unlimited execution privileges.
2. Traditional Kernel Extensions Versus eBPF
Extending operating system functionality has traditionally involved kernel source modifications, loadable kernel modules or userspace mechanisms that interact with existing kernel interfaces.
Kernel modules can provide powerful functionality, including device drivers and new kernel subsystems. However, conventional modules execute with extensive kernel privileges and generally do not undergo the eBPF verifier's program-level safety analysis.
eBPF introduces a different extension model. Programs are loaded through controlled interfaces, verified and attached to supported execution points.
| Characteristic | Kernel module | eBPF program |
|---|---|---|
| Execution model | Native kernel code | Verified BPF instructions, commonly JIT-compiled |
| Safety analysis | Development, review and kernel loading controls | Kernel verifier and program-type restrictions |
| Kernel access | Broad kernel capabilities | Constrained by context, pointer rules and permitted interfaces |
| Execution triggers | Module-defined integration mechanisms | Compatible BPF attachment points |
| Deployment | Loadable where permitted by kernel policy | Dynamic loading and attachment where supported |
| Typical applications | Drivers, filesystems and kernel subsystems | Networking, tracing, security and observability |
Both technologies can be dynamically deployed. The important difference is not simply whether a reboot is required, but the execution model, safety constraints and available functionality.
3. The eBPF Instruction Set and Register Model
eBPF defines a register-based instruction architecture. Compilers translate supported source code into BPF instructions that can be analysed by the verifier and executed by the kernel.
The architecture provides eleven 64-bit registers, identified as R0 through R10. Different registers have defined roles within the BPF calling convention.
Logical field layout of the basic BPF instruction encoding. Some instructions, such as a 64-bit immediate load, occupy two instruction slots. Field interpretation depends on the opcode.
| Instruction class | Engineering purpose |
|---|---|
| Arithmetic and logic | Perform calculations and bitwise operations. |
| Memory loads | Read permitted data from valid memory locations. |
| Memory stores | Write to permitted memory locations. |
| Conditional jumps | Implement comparisons and control-flow decisions. |
| Function calls | Invoke supported helpers or other permitted functions. |
| Exit | Return control and the program's result. |
; Minimal XDP program returning XDP_PASS 0: (b7) r0 = 2 1: (95) exit ; R0 contains the return value. ; XDP_PASS is represented by value 2. ; The packet continues through the networking stack.
The meaning of a return value depends on the program type. A return value representing XDP_PASS in an XDP program does not have the same universal meaning in every BPF execution context.
4. Understanding the Attachment-Point Model
Unlike a conventional userspace service, an attached eBPF program generally does not run continuously in its own execution loop.
Instead, the program is invoked when a compatible execution point is triggered. The kernel provides a context appropriate to that program type.
| Attachment mechanism | Execution trigger | Representative application |
|---|---|---|
| XDP | Packet reception at a supported XDP hook | Early packet processing and filtering |
| TC | Traffic-control ingress or egress processing | Packet classification and policy |
| Tracepoints | Defined kernel tracing events | Structured operating system telemetry |
| Kprobes | Instrumented kernel instruction locations | Dynamic kernel investigation |
| Fentry / Fexit | Supported kernel function entry or exit | Function-level tracing |
| Uprobes | Instrumented userspace code locations | Application execution visibility |
| BPF LSM | Supported Linux Security Module hooks | Security observation and enforcement |
| Cgroup hooks | Supported cgroup-associated operations | Workload-scoped networking and access controls |
Selecting an attachment point is an architectural decision. It determines when the program executes, what context is available, which helpers can be called and whether the program can influence the original operation.
5. From Source Code to Attached Kernel Program
A typical eBPF development workflow begins with source code written in a supported language and compiled into BPF instructions.
The userspace loader creates or references required maps, performs applicable relocations and submits the program to the kernel.
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
SEC("xdp")
int example_xdp(struct xdp_md *ctx)
{
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";
This minimal program returns XDP_PASS for every packet presented to it. It does not inspect packet headers, maintain counters or implement a security policy.
Its purpose is to illustrate the relationship between source code, program type, execution context and return semantics.
A successfully loaded program does not necessarily execute immediately. It must be associated with an appropriate execution point or invoked through a supported mechanism.
6. eBPF Maps and Shared Infrastructure State
Individual program invocations are generally short-lived. However, infrastructure applications frequently need to preserve information between events.
BPF maps provide kernel-managed data structures that can retain configuration, counters, lookup entries and other state.
Illustrative shared map containing workload counters. Programs must reference the same compatible map object and have the required access permissions.
| Map type | Architectural characteristic | Typical application |
|---|---|---|
| Hash | Key-value lookup structure | Flow state and identity lookups |
| Array | Fixed indexed entries | Configuration and counters |
| Per-CPU array / hash | CPU-specific values | Reducing contention for frequent updates |
| LRU hash | Capacity-constrained entries with eviction | Bounded connection or flow tracking |
| LPM trie | Longest-prefix matching | IP prefix and policy lookups |
| Program array | References to compatible BPF programs | Tail-call-based processing pipelines |
| Ring buffer | Shared event transport mechanism | Structured kernel-to-userspace telemetry |
Map selection influences memory consumption, lookup behaviour, concurrency, contention and event delivery characteristics.
A high-frequency global counter, for example, may create contention between CPUs. A per-CPU map can reduce that contention, but the consumer must aggregate the CPU-specific values to obtain a system-wide result.
7. BPF Helpers and Kernel Function Interfaces
BPF programs cannot simply invoke arbitrary kernel functions in the same way that conventional kernel code can.
Instead, the kernel exposes supported interfaces through BPF helpers and, where available, permitted kernel functions known as kfuncs.
State Access
Perform supported map lookups, updates and deletions while respecting map type and access constraints.
Execution Context
Retrieve supported process, task, cgroup and execution information appropriate to the program context.
Time Measurements
Obtain supported kernel timestamps for latency measurements, event correlation and performance analysis.
Event Export
Submit selected event information through compatible ring-buffer or performance-event mechanisms.
Network Processing
Perform supported packet operations, checksum adjustments or redirect decisions where the program type permits.
Kernel Functions
Use explicitly exposed kfunc interfaces subject to kernel version, program type, BTF and verifier constraints.
| Representative helper | Purpose |
|---|---|
| bpf_map_lookup_elem() | Look up a map entry. |
| bpf_map_update_elem() | Create or update a permitted map entry. |
| bpf_ktime_get_ns() | Obtain a monotonic kernel time measurement. |
| bpf_get_current_pid_tgid() | Retrieve current task PID and TGID information. |
| bpf_ringbuf_output() | Copy event data into a compatible ring buffer. |
| bpf_redirect() | Request supported network packet redirection. |
Not every helper is available to every BPF program. Engineers must validate the program type, kernel capabilities and verifier requirements before designing a particular processing mechanism.
8. The Verifier and Constrained Execution Model
Executing programmable logic inside the operating system introduces significant reliability and security considerations.
Before a BPF program can be accepted, the verifier analyses its instructions, control flow, register state, pointer properties and memory-access behaviour.
Memory Safety
The verifier evaluates whether memory operations are valid for the relevant pointer type, object and established bounds.
Control Flow
Program paths are analysed against execution constraints. Supported bounded loops and iteration mechanisms must satisfy applicable verification rules.
Register Tracking
Register values, scalar ranges, pointer properties and initialisation state contribute to verifier analysis.
Interface Validation
Helper and kfunc calls are checked against permitted interfaces and argument requirements.
An accepted program can still implement an incorrect policy, consume excessive resources or collect inappropriate data. Verifier and JIT implementation vulnerabilities are also possible. Kernel patching, privilege controls and operational validation remain essential.
9. JIT Compilation and Infrastructure Overhead
On supported architectures, the BPF JIT compiler translates accepted BPF instructions into native processor instructions.
This avoids the need to interpret each BPF instruction during normal JIT-compiled execution.
However, overall overhead depends on considerably more than the instruction execution mechanism.
Event Frequency
A program attached to a high-frequency networking or scheduling hook may execute millions of times during busy periods.
Program Complexity
Map lookups, memory operations, calculations and helper calls contribute to execution cost.
Telemetry Volume
Exporting every event can create significant userspace processing, memory and storage requirements.
Assumption: average incremental execution cost of 200 nanoseconds per invocation.
Percentage of one CPU core's execution capacity, calculated from event rate multiplied by assumed per-event cost. These are synthetic calculations, not measured eBPF benchmarks.
CPU core equivalents =
event_rate × average_execution_time_seconds
Example:
Event rate = 2,000,000 events/sec
Execution cost = 200 ns/event
= 0.0000002 sec/event
CPU consumption = 2,000,000 × 0.0000002
= 0.4 CPU core equivalents
Equivalent cost = 40% of one CPU core
Actual CPU consumption must be measured under representative workloads. Cache behaviour, concurrency, program composition, hook overhead and telemetry processing can substantially change the result.
10. BTF and Compile Once — Run Everywhere
Linux kernel structures can change between kernel releases and distribution builds. Programs that depend on particular internal structure layouts may therefore require compatibility adjustments.
BPF Type Format, or BTF, provides compact type information that can describe kernel and BPF program data structures.
CO-RE, meaning Compile Once — Run Everywhere, uses relocation information and target kernel type metadata to adapt supported program references during loading.
CO-RE improves portability, but it does not automatically make every program compatible with every Linux kernel.
Required program types, attachment points, helpers, kfuncs, kernel configuration and security permissions must still be available.
11. Building a Process Execution Counter
Consider an engineering team that wants to measure how frequently processes successfully execute new programs across a Linux infrastructure environment.
Instead of exporting a detailed event for every execution, the team can attach a BPF program to an appropriate execution tracepoint and maintain counters inside a map.
$ sudo bpftrace -e \
'tracepoint:sched:sched_process_exec
{
@executions[comm] = count();
}
interval:s:10
{
print(@executions);
clear(@executions);
}'
This example uses bpftrace to aggregate successful program execution events by the current task's command name and periodically print the counters.
@executions[nginx]: 4 @executions[python3]: 12 @executions[bash]: 18 @executions[curl]: 31 @executions[healthcheck]: 45
These counters provide useful aggregate evidence without requiring the complete details of every event to be exported.
However, a command name is not a reliable unique security identity. It does not establish executable integrity, process ancestry or Kubernetes workload ownership. Additional context is required for security investigations.
Aggregation can reduce telemetry volume and downstream processing costs. Detailed event export provides richer forensic evidence. Production designs must balance both requirements.
12. Troubleshooting an eBPF Deployment
Suppose a newly deployed observability agent starts successfully, but its dashboard reports no process execution events.
The absence of events does not immediately establish that the kernel is inactive or that the observability platform is defective.
Engineers should investigate the complete execution and telemetry chain.
| Investigation layer | Potential issue | Evidence to inspect |
|---|---|---|
| Kernel compatibility | Required capability unavailable | Kernel version, configuration and feature probe |
| Program loading | Verifier rejection or insufficient privilege | Loader errors and verifier diagnostics |
| Attachment | Program loaded but not attached | Attachment-specific inspection and agent logs |
| Event generation | Expected execution point not triggered | Controlled test activity and probe selection |
| Program logic | Filters exclude expected events | Map configuration and program counters |
| Event transport | Buffer saturation or failed event submission | Drop counters and consumer health |
| Userspace processing | Decoding or metadata enrichment failure | Agent diagnostics and event schema validation |
| Backend export | Collector or storage connectivity failure | Exporter errors and backend ingestion metrics |
$ uname -r $ sudo bpftool feature probe $ sudo bpftool prog show $ sudo bpftool map show $ sudo bpftool link show $ sudo bpftrace -l \ 'tracepoint:sched:sched_process_exec' $ ls -l /sys/kernel/btf/vmlinux
The available output depends on installed tooling, permissions and kernel capabilities. Not all attachment mechanisms are represented by BPF link objects, and the presence of kernel BTF alone does not guarantee compatibility with a particular program.
eBPF as a Programmable Infrastructure Foundation
Understanding eBPF requires more than recognising it as a modern Linux networking or security technology.
Engineers must understand the relationship between instructions, verification, attachment points, execution context, kernel-managed state and userspace control applications.
These components form the architectural foundation used by modern cloud-native networking, runtime security and observability platforms.
Select the correct execution point. Understand the available context. Validate the program's capabilities. Measure the resulting infrastructure behaviour.
eBPF Kernel Architecture Explorer
Explore the programmable intelligence layer inside the Linux kernel. Attach eBPF programs, generate operating-system events, inspect kernel execution points and follow telemetry into userspace security and observability platforms.
Linux Kernel — Interactive Cutaway
SIMULATION ONLINEKernel Program Registry
| Hook | State | Mode | Hits |
|---|
Each registry entry represents one conceptual attached program. Real Linux systems may support multiple programs and different attachment mechanisms.
Kernel Event Transport
Engineering Event Console
Guided Engineering Investigations
0 / 3 completedObserve a Process
Attach a tracepoint program, execute a process and consume the resulting telemetry record in userspace.
Enforce Kernel Security
Attach a BPF LSM enforcement program and attempt access to a file covered by the demonstration deny policy.
Investigate Telemetry Loss
Attach an XDP observation program and generate a burst exceeding the simplified ring-buffer capacity.
Observation and enforcement are different capabilities.
Tracepoints, kprobes and uprobes primarily provide instrumentation. XDP and suitable TC programs can make packet-processing decisions. BPF LSM programs can participate in security authorization. These capabilities depend on program type, attachment point, kernel configuration and privileges. A tracing program does not automatically become a security enforcement program.
Linux Kernel, Userspace and eBPF Execution
Exploring the operating system execution boundaries, processor privilege transitions and kernel subsystems that form the foundation of eBPF-powered infrastructure security and observability.
Conceptual Linux execution architecture. eBPF programs execute at selected hooks within or associated with kernel subsystems. They are not a separate operating system layer through which every operation must pass.
1. Understanding the Linux Execution Boundary
Linux separates ordinary application execution from privileged operating system functionality. This separation is fundamental to system stability, memory protection and security.
Applications execute in userspace and normally cannot directly manipulate hardware, modify kernel memory or perform privileged processor operations. They request operating system services through controlled interfaces.
The Linux kernel manages processor scheduling, virtual memory, filesystems, networking, device drivers and security decisions.
Userspace
Application code, databases, web servers, container workloads, libraries and eBPF control-plane agents execute with restricted processor privileges.
Kernelspace
The operating system executes privileged functionality, manages hardware resources and enforces operating system access controls.
eBPF can observe selected operations at the operating system level, where application requests become process, network, filesystem and security activity.
2. CPU Privilege Levels and Execution Modes
Modern processors provide hardware mechanisms that distinguish privileged operating system execution from restricted application execution.
On conventional x86-64 Linux systems, userspace normally executes at privilege level Ring 3, while the kernel executes at Ring 0.
Other processor architectures provide equivalent mechanisms using different terminology. For example, Arm AArch64 Linux commonly uses EL0 for applications and EL1 for the operating system.
Conventional x86 privilege model. Linux primarily uses Ring 0 and Ring 3; Rings 1 and 2 are shown for architectural context.
Although kernel-hosted eBPF programs execute in a privileged environment, they do not receive unrestricted access to every privileged processor operation or kernel function.
Their available capabilities remain constrained by the BPF execution model, verifier and program-type-specific interfaces.
3. System Calls and the Linux Service Interface
A system call is a controlled mechanism through which an application requests functionality from the operating system.
When an application opens a file, creates a socket, starts a new executable or requests certain memory operations, it may invoke a system call.
| System call | Purpose | Security and observability relevance |
|---|---|---|
| execve() | Replace the current process image. | Executable activity and process investigation. |
| openat() | Open a file relative to a directory descriptor. | File access monitoring. |
| connect() | Initiate or establish a socket association. | Outbound communication visibility. |
| accept4() | Accept an incoming socket connection. | Inbound service activity. |
| mmap() | Create a virtual memory mapping. | Memory usage and executable mapping investigation. |
| clone() / clone3() | Create a task with specified sharing semantics. | Process and thread lifecycle monitoring. |
| bpf() | Perform supported BPF object and program operations. | Program loading, map management and BPF administration. |
Simplified file-open execution path. Actual VFS processing can involve multiple security checks, filesystem-specific operations and error paths.
An entry tracepoint can reveal that an operation was attempted. An exit tracepoint can reveal its return value. A security hook may provide additional object context and, where supported, enforcement capabilities.
Observing an openat() entry event does not establish that a file was successfully opened. Engineers must distinguish attempted operations, security decisions and completed outcomes.
4. Process Scheduling and CPU Context Switching
Linux manages runnable tasks and distributes execution across available processors. The scheduler determines which eligible task should execute according to scheduling policies, priorities and resource constraints.
When the processor switches between tasks, execution state must be preserved and restored. This is known as a context switch.
Running
The task is currently executing on a processor.
Runnable
The task is eligible to execute but may be waiting for processor capacity.
Blocked or Sleeping
The task is waiting for an event, resource or other condition before becoming runnable.
eBPF programs attached to appropriate scheduling events can help engineers measure runnable latency, task execution time, context-switch frequency and off-CPU behaviour.
A slow application may be waiting for CPU time rather than experiencing slow application code or network congestion.
5. Process Memory, Page Tables and Kernel Protection
Each conventional userspace process operates within a virtual address space. The processor's memory management unit and operating system page tables translate virtual addresses and enforce memory-access permissions.
Virtual address spaces allow processes to use similar virtual addresses while accessing different physical memory pages.
Illustrative page mappings. Actual address translation uses architecture-specific page-table structures, translation caches and permission checks.
BPF programs must respect verifier-enforced pointer and memory-access constraints. Access to kernel or userspace data depends on the program type, pointer provenance and permitted access mechanisms.
Page Faults
Occur when an address access requires operating system handling, such as demand paging or resolving a protection violation. Not every page fault requires storage I/O.
Memory Pressure
Can cause reclaim activity, allocation delays, swapping where configured and potentially out-of-memory handling.
6. Interrupts, Softirqs and Network Processing
Kernel execution is not driven exclusively by application system calls.
Hardware devices can generate interrupts. The kernel also uses deferred processing mechanisms to handle work outside the immediate interrupt handler.
In Linux networking, NAPI provides a mechanism for processing received packets through polling, reducing the need to handle every packet through a separate hardware interrupt.
Representative driver-native XDP receive path. Generic XDP and hardware-offloaded XDP have different execution placement. Other XDP actions are omitted from this simplified diagram.
Packet reception, deferred processing and other asynchronous events may occur independently of a particular application system call. The current task is not necessarily the workload responsible for the observed packet or operation.
7. Understanding eBPF Execution Contexts
The execution context determines what an attached BPF program can observe and which operations it can perform.
A tracing program executing in process context has different environmental constraints from a networking program executing in an early receive path.
| Execution context | Representative attachment | Engineering consideration |
|---|---|---|
| Process context | System call tracepoint | Current task information can often provide useful attribution. |
| Network receive path | Native XDP | Packet metadata is available; application identity may not be established. |
| Scheduling event | sched_switch | Previous and next task information is relevant to scheduling analysis. |
| Kernel function execution | Fentry / kprobe | Available arguments and context depend on the attachment mechanism. |
| Security decision point | BPF LSM | Supported hooks may influence the security decision. |
| Sleepable BPF context | Supported sleepable tracing or LSM programs | Selected additional operations are permitted under applicable restrictions. |
Ordinary BPF programs cannot assume that blocking operations are permitted. Sleepable BPF programs are a specific capability available for supported program types and attachment contexts.
Engineers must select the attachment point according to the information required, the desired enforcement behaviour and the execution constraints of the underlying kernel path.
8. Linux Namespaces and Container Visibility
Containers commonly use Linux namespaces to provide isolated views of operating system resources.
A process inside a container can have a different view of process identifiers, network interfaces, mount points and other resources from a process in another namespace.
Conventional containers share the host kernel. Namespace sharing varies with container and Kubernetes configuration. VM-backed container isolation can introduce a different architecture.
| Namespace | Isolation characteristic |
|---|---|
| PID | Isolated views of process identifiers. |
| Network | Network devices, routing tables, sockets and related resources. |
| Mount | Filesystem mount-point visibility. |
| User | User and group identifier mappings and associated capabilities. |
| IPC | Selected interprocess communication resources. |
| UTS | Hostname and NIS domain name. |
| Cgroup | Virtualised views of cgroup hierarchy paths. |
| Time | Offsets for selected system clocks. |
Host-level BPF instrumentation can provide visibility into activity originating from multiple containers when the selected hooks and permissions support that visibility.
However, collecting a host process identifier is not the same as identifying the Kubernetes pod, namespace, deployment or service account responsible for the activity.
9. Cgroups, Resource Accounting and Workload Identity
Control groups, commonly called cgroups, organise Linux tasks into hierarchical groups for resource accounting and control.
Modern container platforms use cgroups to manage CPU, memory and other resource constraints.
CPU Controller
Supports CPU accounting, relative weights and bandwidth constraints through applicable cgroup interfaces.
Memory Controller
Provides memory accounting, protection thresholds and resource limits.
I/O Controller
Supports applicable storage I/O accounting and resource-control mechanisms.
BPF programs can use supported cgroup information to help associate kernel events with workload execution contexts.
Certain BPF program types can also be attached to cgroups to observe or control supported networking and socket operations.
Namespaces primarily isolate resource views. Cgroups organise tasks for resource accounting, control and supported policy attachment. Neither mechanism alone provides a complete container security boundary.
10. From Kernel Event to Kubernetes Identity
One of the most important challenges in cloud-native observability is translating low-level operating system evidence into meaningful application and workload context.
A kernel event may contain a task identifier, timestamp, cgroup identifier and operation-specific information. A userspace agent can enrich that information using container runtime and Kubernetes metadata.
{
"event": "process_exec",
"host_pid": 28471,
"container_pid": 17,
"cgroup_id": 84217,
"process": "curl",
"executable": "/usr/bin/curl",
"parent_process": "sh",
"kubernetes": {
"namespace": "payments",
"pod": "payment-api-7d8f9",
"container": "api",
"service_account": "payment-service"
}
}
This enriched event is significantly more useful than an isolated process identifier. It provides infrastructure context that can support workload-specific investigation and policy evaluation.
Production systems must account for PID reuse, container termination, metadata caching, event ordering and attribution errors.
11. Following an Application Network Request
Consider a Kubernetes application that initiates an outbound TCP connection to another service.
The operation can generate evidence at multiple points across the userspace application, system call interface, socket layer, network stack and packet-processing datapath.
Conceptual outbound execution path with representative attachment points. Exact hook ordering depends on the protocol, kernel version, routing configuration and network datapath.
These observation points answer different engineering questions.
Application Intent
Which task attempted to establish a connection, and which destination did it request?
Policy Decision
Did an applicable socket or security policy permit, modify or reject the operation?
Network Behaviour
Were packets transmitted, retransmitted, redirected or dropped along the datapath?
Application Outcome
Did the connection succeed, fail, time out or remain in progress?
12. Inspecting the Execution Environment
Before deploying advanced eBPF instrumentation, engineers should understand the Linux environment in which their programs will execute.
# Kernel and processor architecture uname -a lscpu # Process and thread information ps -eLo pid,tid,psr,stat,comm # Namespace inspection lsns readlink /proc/self/ns/pid readlink /proc/self/ns/net # Cgroup membership cat /proc/self/cgroup # Cgroup filesystem type stat -fc %T /sys/fs/cgroup # CPU and memory activity vmstat 1 # Pressure stall information, if available cat /proc/pressure/cpu cat /proc/pressure/memory cat /proc/pressure/io # Network socket inspection ss -ntp # Available BPF capabilities sudo bpftool feature probe
These commands provide foundational evidence about process execution, resource pressure, namespace isolation, socket state and available BPF functionality.
sudo bpftrace -e '
tracepoint:raw_syscalls:sys_enter
{
@calls[comm] = count();
}
interval:s:10
{
print(@calls);
clear(@calls);
}'
This example counts system call entry events by the current task's command name and periodically reports aggregate values.
Because system call entry is potentially a high-frequency event source, engineers should evaluate instrumentation overhead before using broad tracing in production.
The command requires appropriate privileges, installed tooling and a kernel that exposes the required tracepoint.
13. Is the Application Slow or Is the Kernel Under Pressure?
Consider a production Kubernetes service experiencing intermittent request latency. Application engineers initially suspect database or network congestion.
Infrastructure telemetry, however, reveals significant CPU scheduling delays within the affected workload.
Synthetic teaching data. Metrics are illustrative and do not represent measured production results.
Request latency remains within its expected range.
Workload CPU demand increases during a traffic surge.
Network and database latency remain comparatively stable.
Scheduling instrumentation and cgroup CPU accounting support a resource-contention hypothesis.
Engineers evaluate whether a controlled CPU allocation change reduces throttling and application latency.
# Read from the affected workload's cgroup $ cat cpu.max 50000 100000 $ cat cpu.stat usage_usec 184729300 user_usec 151284100 system_usec 33445200 nr_periods 1200 nr_throttled 816 throttled_usec 42810000 # Illustrative cumulative ratio: # 816 / 1200 = 68% # CPU bandwidth: # 50000 / 100000 = 0.5 CPU equivalents
Cgroup counters are cumulative. Production investigation should normally calculate counter differences over a defined observation interval rather than treating a lifetime ratio as a current measurement.
Kernel-level evidence can distinguish resource contention from application, storage and network problems. Correlation alone does not prove the root cause; controlled validation is required.
The Linux Kernel as an Infrastructure Observation Plane
Understanding eBPF requires understanding the operating system in which it executes.
CPU privilege transitions, system calls, process scheduling, memory management, asynchronous network processing, namespaces and cgroups all influence the evidence that an eBPF-powered platform can collect.
Modern runtime security and observability systems combine this low-level evidence with workload metadata to provide meaningful infrastructure visibility.
Understand the execution boundary. Select the appropriate observation point. Preserve workload context. Correlate evidence across infrastructure layers. Validate the engineering conclusion.
Kernel Execution Journey Simulator
Follow application requests through the Linux execution architecture. Observe privilege transitions, kernel functions, security decisions and eBPF instrumentation as individual operating-system journeys unfold inside an interactive processor and kernel cutaway.
Linux Execution Architecture
KERNEL DIGITAL TWINCPU Privilege Boundary
Applications normally execute in user mode. A system call transfers execution into the kernel through a controlled architecture-specific entry mechanism.
Execution Timeline
Conceptual Execution Stack
Current logical execution context, with the active frame at the top.
Telemetry Transport
Execution Cost Analysis
Compare the selected execution path with and without its configured instrumentation. All costs are illustrative model values, not Linux performance measurements.
0 ns
Initialize a journey to calculate the illustrative instrumentation cost.
0
A privilege transition is not necessarily a scheduler context switch. The same thread may continue executing after entering the kernel.
Kernel Execution Console
Guided Engineering Investigations
0 / 4 completedCross the Privilege Boundary
Execute an uninstrumented file-access system call. Observe the transition into kernel mode and the return to the original userspace execution context.
Instrument Kernel Execution
Enable tracepoints and a kernel function probe. Execute a file-read journey and examine the additional eBPF executions and telemetry records.
Observe a Userspace Function
Instrument a userspace library function using a uprobe. Investigate why a userspace attachment can trigger kernel-controlled eBPF execution without a system call.
Investigate a Denied Operation
Enable BPF LSM enforcement and attempt restricted file access. Identify the authorization decision and the resource operation that never executes.
Kernel execution is not the same as a context switch.
A system call normally transfers the current thread into privileged kernel execution. A scheduler context switch changes the executing task and may occur independently. Similarly, uprobes can trigger kernel-controlled instrumentation through a probe exception rather than an application-issued system call. eBPF programs execute within the constraints of their program type and attachment context; they do not acquire unrestricted kernel privileges.
eBPF Program Lifecycle, Verifier and JIT Compilation
From high-level source code to verified kernel execution: exploring the compilation pipeline, BPF instruction set, portable type information, static program analysis, native machine-code generation and runtime attachment.
Representative libbpf-based program lifecycle. Loading and attachment details vary by program type, kernel capabilities and deployment framework.
1. From Source Code to Kernel Execution
An eBPF program is not normally compiled into a conventional Linux userspace executable. Instead, its logic is translated into instructions for the BPF virtual instruction set.
Before a program can execute at a supported kernel attachment point, the operating system must accept the program through its loading and verification mechanisms.
A successfully loaded BPF program may exist as a kernel object without being attached to an event source. Loading, attachment and actual invocation are distinct lifecycle stages.
2. Clang, LLVM and the BPF Instruction Target
Clang and LLVM provide a widely used toolchain for compiling C-based eBPF programs. LLVM can target the BPF instruction set rather than the native instruction set of the build machine.
Other languages and frameworks can also produce BPF programs. The essential requirement is that the resulting instructions and associated metadata satisfy the target kernel's loading requirements.
clang -O2 -g -target bpf \ -c program.bpf.c \ -o program.bpf.o # Inspect ELF sections llvm-readelf -S program.bpf.o # Inspect BPF instructions llvm-objdump -d program.bpf.o
Optimisation can influence instruction count, control flow and verifier complexity. Debug information can support generation of BTF metadata and improve program inspection.
Actual compilation may require additional include paths, generated headers and target architecture definitions.
3. Understanding BPF Bytecode and Instruction Encoding
The BPF instruction set defines operations for arithmetic, register manipulation, memory access, conditional branching and supported function calls.
Most BPF instructions use a fixed eight-byte encoding. Certain wide immediate operations occupy two instruction slots.
Logical field representation. Register nibble ordering and multi-byte field representation depend on the relevant BPF endianness conventions.
Source: return XDP_PASS; BPF instructions: 0: r0 = 2 1: exit Meaning: R0 receives the return value. EXIT terminates program execution. For XDP, return value 2 means XDP_PASS.
The interpretation of a return value depends on the program type. A return value used by an XDP program does not necessarily have the same meaning in a tracing, socket or security program.
4. Registers, Calling Conventions and Stack Memory
The BPF instruction architecture exposes eleven registers, R0 through R10. These registers provide the foundation for computation, argument passing, pointer tracking and function execution.
R1 initially contains a pointer to the program context for conventional BPF entry points. The available context fields depend on the program type.
Following a conventional helper call, registers R1 through R5 are treated as clobbered, while R6 through R9 preserve their values according to the calling convention.
Conventional BPF stack accesses use negative offsets from R10. A commonly encountered stack limit is 512 bytes per BPF function frame, with additional restrictions depending on call structure and kernel implementation.
5. ELF Objects, libbpf and Program Loading
Compiled BPF programs are commonly packaged in Executable and Linkable Format objects.
An ELF object can contain program instructions, map definitions, symbol information, relocation records and type metadata.
Program Sections
Contain instructions associated with program entry points and supported attachment conventions.
Map Definitions
Describe shared kernel data structures used by BPF programs and authorised userspace components.
Type Information
Describes data structures, function types and other metadata in a compact representation.
Relocations
Allow the loader to resolve references and adapt supported instructions to the target system.
Licence Metadata
Supplies licence information relevant to the availability of GPL-restricted BPF functionality.
Kernel Object Handles
Successful object creation or program loading returns file descriptors through kernel interfaces.
libbpf provides userspace functionality for opening BPF objects, preparing maps, applying relocations, loading programs and performing supported attachments.
Open BPF ELF object
|
v
Parse sections and metadata
|
v
Resolve supported relocations
|
v
Prepare required BPF maps
|
v
Load programs through bpf()
|
v
Receive program file descriptors
|
v
Attach programs to selected hooks
The exact internal sequence depends on the object, map dependencies, relocation requirements and libbpf implementation.
6. BTF and Compile Once – Run Everywhere
Linux kernel data structures can change between kernel versions and configurations.
A field located at one byte offset in a particular kernel structure may appear at a different offset in another kernel build.
BPF Type Format, or BTF, provides compact type metadata. CO-RE uses appropriate type information and relocation records to adapt supported BPF accesses to the target kernel.
Synthetic structure layout demonstrating field-offset relocation. CO-RE also supports other relocation categories, including field and type existence checks.
# Check for kernel BTF ls -l /sys/kernel/btf/vmlinux # Generate a C representation of kernel types bpftool btf dump \ file /sys/kernel/btf/vmlinux \ format c > vmlinux.h # Inspect available BTF objects sudo bpftool btf show
CO-RE improves portability across compatible kernel environments. It cannot guarantee that a missing attachment point, unsupported helper, unavailable kernel feature or incompatible program requirement will become usable.
7. The eBPF Verifier
The verifier is one of the central security mechanisms of the Linux BPF execution environment.
Rather than simply trusting a compiled program, the kernel analyses its instructions and abstract execution states before permitting supported execution.
The verifier reasons about register types, scalar ranges, pointer provenance, stack initialisation, memory bounds, control flow and applicable function-call restrictions.
| Verification domain | Engineering objective |
|---|---|
| Control flow | Validate supported instruction paths and branching behaviour. |
| Register state | Track initialisation, scalar values and pointer types. |
| Memory access | Establish applicable bounds, alignment and access validity. |
| Stack state | Track written bytes, spilled registers and supported reads. |
| Function calls | Validate supported helper and kfunc arguments and restrictions. |
| Execution complexity | Keep verification within supported analysis limits. |
| Resource lifetime | Enforce applicable reference acquisition and release rules. |
Verification is an abstract analysis process, not a test that executes the program against every possible real packet or application event.
An accepted program can still implement an incorrect security policy, discard legitimate traffic or impose unacceptable runtime overhead. Verification does not replace functional testing or production governance.
8. Register State Tracking and Scalar Range Analysis
The verifier tracks information about registers as instructions transform their values.
A register may contain an ordinary scalar value, a pointer to program context, a packet pointer, a map-value pointer or another supported pointer category.
Scalar analysis can track signed and unsigned bounds and known or unknown bits. Conditional branches can refine the information available along different execution paths.
Simplified unsigned scalar analysis. The real verifier maintains additional state, including relationships between pointer and scalar values.
If a later memory access depends on R2, the verifier can use the refined range to reason about the access.
However, a scalar range alone is not sufficient to establish that a pointer-based access is valid. Pointer provenance and object-specific bounds must also be satisfied.
9. Pointer Tracking and Packet Bounds Validation
An XDP program may receive access to packet data through pointers derived from its program context.
Before reading a packet header, the program must establish that the requested bytes are within the accessible packet region.
Conceptual packet layout, not drawn to byte scale.
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
SEC("xdp")
int inspect_eth(struct xdp_md *ctx)
{
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
return XDP_PASS;
if (eth->h_proto == bpf_htons(ETH_P_IP))
return XDP_PASS;
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";
This example demonstrates the source-level bounds checking pattern used before accessing an Ethernet header. It deliberately passes all packets.
Because both branches return the same result, an optimising compiler may remove the header access and associated conditional logic. A production inspection program would use the extracted information for a meaningful operation, such as updating an appropriate counter.
Certain helpers can modify packet layout or invalidate previously established packet-pointer information. Programs must re-establish the required pointer state and bounds before subsequent accesses.
10. Map Lookup Results and Nullable Pointers
BPF maps allow programs to access persistent state across invocations and communicate with other authorised components.
A map lookup can return a valid value pointer or a null pointer when the requested element is unavailable.
Unchecked lookup
value = bpf_map_lookup_elem(
&counts, &key);
return *value;
The lookup result may be null. Dereferencing without establishing a valid pointer state can cause verifier rejection.
Null-aware access
value = bpf_map_lookup_elem(
&counts, &key);
if (!value)
return 0;
return *value;
The conditional branch establishes a non-null path. The remaining access must still satisfy map-value size and program-specific rules.
Illustrative C fragments rather than complete BPF programs. Return-value semantics depend on the selected program type.
11. Bounded Loops, Branches and Verification Complexity
Modern Linux BPF implementations support several mechanisms for expressing repeated execution, including bounded loops and supported iteration interfaces.
The verifier must be able to establish the applicable execution constraints while keeping its own analysis within supported complexity limits.
Complex branching inside a loop can significantly increase the number of abstract states the verifier must analyse.
Consequently, a relatively short source program can still encounter verification complexity limits. Conversely, a larger program with straightforward state transitions may be easier to analyse.
Bounded Loops
Express repeated execution with a termination condition that can satisfy verifier analysis.
Loop Helpers
Supported helpers such as bpf_loop provide callback-based iteration under applicable rules.
Open-Coded Iterators
Supported iterator mechanisms can enable efficient traversal and different verification strategies on compatible kernels.
12. BPF Helpers, Kernel Functions and Resource Lifetimes
BPF programs do not receive unrestricted access to arbitrary kernel functions.
Instead, they can use supported helper functions and eligible kernel functions, commonly called kfuncs, subject to program-type and verifier rules.
| Interface | Representative purpose | Important restriction |
|---|---|---|
| bpf_map_lookup_elem | Retrieve a map element. | Nullable return pointer and map access rules. |
| bpf_ktime_get_ns | Retrieve a monotonic time value. | Availability depends on supported program context. |
| bpf_get_current_pid_tgid | Retrieve current task identifiers. | Current task is not always the event's responsible workload. |
| bpf_ringbuf_reserve | Reserve space for an event record. | Successful reservations require appropriate completion. |
| bpf_tail_call | Transfer execution to an eligible BPF program. | Program-array compatibility and tail-call limits apply. |
| Supported kfuncs | Expose selected kernel functionality to BPF. | Availability, argument types and lifetime rules vary. |
Resource tracking is particularly important for interfaces that return references or reserved memory requiring explicit completion or release.
13. Just-In-Time Compilation
Once a BPF program satisfies the applicable verification requirements, the kernel can use a Just-In-Time compiler to translate BPF instructions into native processor instructions.
This translation allows supported BPF programs to execute directly as native code rather than requiring instruction-by-instruction interpretation.
A target kernel uses the relevant architecture-specific execution backend. The diagram shows alternative processor architectures, not simultaneous compilation for both processors.
Interpreter
Executes BPF instructions through an interpreter where the kernel configuration and program type support that execution mode.
JIT Compiler
Generates native machine instructions appropriate to the target processor architecture.
# Inspect JIT configuration where exposed sysctl net.core.bpf_jit_enable # List loaded programs sudo bpftool prog show # Inspect translated BPF instructions sudo bpftool prog dump xlated id 42 # Inspect JIT-generated native instructions sudo bpftool prog dump jited id 42
Program ID 42 is an example and must be replaced with an actual loaded program identifier. Native-code inspection depends on kernel support, privileges and security configuration.
Execution frequency, map operations, event generation, memory access, helper calls and program complexity can all influence infrastructure overhead.
14. Program Attachment, Invocation and Object Lifetime
After loading, an eBPF program can be associated with an appropriate attachment point using a mechanism supported by its program type.
Some attachments use BPF links, which represent attachment relationships as kernel objects. Other attachment mechanisms use different interfaces and lifetime semantics.
BPF objects are reference counted. Closing a userspace file descriptor does not necessarily destroy an object if another reference remains.
Pinning supported objects in the BPF filesystem can preserve references independently of the creating process.
Pinning is not persistent storage across a normal system reboot. Production agents must account for object recreation and attachment restoration.
sudo bpftool prog show sudo bpftool map show sudo bpftool link show sudo bpftool net show # Inspect BPF filesystem mount findmnt /sys/fs/bpf # Inspect pinned object paths sudo ls -l /sys/fs/bpf
15. Understanding Verifier Rejection and Loading Failures
A BPF program can compile successfully and still fail to load into the target kernel.
Compilation validates source-language and compiler requirements. Kernel loading introduces additional requirements involving permissions, available features, program compatibility and verifier analysis.
| Failure category | Potential cause | Investigation direction |
|---|---|---|
| Compilation failure | Missing headers or unsupported source construct. | Inspect compiler diagnostics and build environment. |
| Relocation failure | Missing or incompatible target type information. | Inspect BTF, CO-RE requirements and target kernel. |
| Invalid memory access | Missing bounds check or invalid pointer state. | Inspect verifier register state and failing instruction. |
| Uninitialised register | Register read without a valid prior assignment. | Review instruction paths and function-call conventions. |
| Unsupported function | Helper or kfunc unavailable for the program context. | Check program type and kernel capabilities. |
| Complexity limit | Excessive abstract execution-state exploration. | Simplify control flow or select suitable iteration mechanisms. |
| Permission failure | Insufficient capabilities or security restrictions. | Review deployment privileges and kernel policy. |
| Attachment failure | Missing hook or incompatible attachment mechanism. | Inspect loaded program state and attachment availability. |
Program: packet_inspector Instruction: 12: r2 = *(u16 *)(r1 + 12) Abstract register state: R1 = packet pointer Proven accessible range = 0 bytes Diagnostic: Packet access not proven safe Result: PROGRAM LOAD REJECTED Investigation: Establish the required packet bounds before accessing the Ethernet header.
This is a simplified diagnostic representation, not verbatim output from a particular Linux kernel version.
The instruction where rejection occurs may be downstream of the operation that caused the invalid register or pointer state. Engineers should examine the preceding execution path rather than only the final error message.
16. Why Does the Same eBPF Agent Work on One Node but Fail on Another?
Consider a Kubernetes environment in which a runtime security agent is deployed across two worker-node groups.
The agent successfully loads its BPF programs on the first group, while selected programs fail during startup on the second group.
Program loaded
Kernel BTF: Available
Required attachment: Available
Required BPF feature: Available
Verification: Accepted
Runtime events: Observed
Selected program unavailable
Kernel BTF: Available
Required attachment: Available
Required BPF feature: Unavailable
Verification or loading: Failed
Runtime events: Missing
Synthetic incident illustrating feature incompatibility despite the availability of BTF and CO-RE support.
Monitoring reveals missing event sources on one worker-node group.
Agent logs distinguish the loading failure from downstream event-export problems.
Engineers inspect supported program types, helpers, kernel configuration and BTF metadata.
The same portable object cannot satisfy all runtime requirements on the affected kernel.
Evaluate a compatible program variant, supported fallback mechanism or approved kernel upgrade.
Verify that expected operations generate the required security evidence on both node groups.
# Compare kernel versions uname -r # Compare available BPF capabilities sudo bpftool feature probe kernel # Inspect kernel BTF availability ls -l /sys/kernel/btf/vmlinux # Inspect loaded programs and attachments sudo bpftool prog show sudo bpftool link show sudo bpftool net show # Inspect service logs for the actual agent journalctl -u YOUR_AGENT_SERVICE --since "15 minutes ago"
For a Kubernetes-managed agent, the equivalent investigation may require inspecting the relevant DaemonSet pods, container logs and node placement rather than a systemd service.
A running userspace agent does not prove that every required BPF program loaded, attached and generated the expected events. Monitor each of these lifecycle stages independently.
From Programmable Logic to Controlled Kernel Execution
The eBPF execution lifecycle combines compiler infrastructure, portable object metadata, userspace loading, kernel verification, native execution and event-driven attachment.
The verifier establishes applicable program safety constraints before execution. BTF and CO-RE improve portability, while JIT compilation enables native processor execution on supported systems.
Production engineering requires more than a successfully compiled program. It requires compatible kernel features, appropriate privileges, correct attachment, validated runtime behaviour and continuous operational visibility.
Compile the program. Resolve its dependencies. Establish safe execution. Attach to the appropriate hook. Verify real runtime behaviour.
eBPF Program Lifecycle Lab
Enter the Linux kernel's programmable execution architecture. Investigate how eBPF programs are prepared, checked, compiled, attached and executed. Diagnose representative verifier failures, repair unsafe program patterns and inspect the resulting kernel state.
Programmable Kernel Lifecycle
INTELLIGENCE CHAMBEReBPF Verifier
The verifier checks the properties of an eBPF program before permitting it to load. Its analysis considers register types, pointer safety, control flow and permitted helper calls.
Program Source Workbench
TEACHING SUBSETEdit the example or apply the safe correction. Only the predefined source variants are recognized by this simulator. Arbitrary C code is not compiled or verified.
Representative eBPF Instructions
ILLUSTRATIVE DISASSEMBLYInstruction listings illustrate the selected safety issue. They are not actual compiler output or executable bytecode.
Awaiting compilation...
Verifier Safety Analysis
Awaiting analysis
Compile and prepare a program before submitting it to the conceptual verifier.
Verifier and Loader Console
Abstract Register State
Selected representative register states at the relevant verification point. These are not a complete verifier trace.
| Register | Abstract type | Safety evidence |
|---|
R0 is used for return values. R1–R5 carry function arguments, R6–R9 are callee-saved registers, and R10 is the read-only frame pointer. The verifier tracks initialization, types and ranges across possible paths.
Kernel Map Inspection
Conceptual counter map maintained across matching invocations of the attached program.
| Map type | Conceptual counter map |
|---|---|
| Map updates | 0 |
| Non-matching events | 0 |
| Last program result | — |
Maps can retain state between program invocations. Actual map lifetime depends on references, pinning and loader behaviour. This laboratory clears its conceptual map when a new program is prepared.
Guided Verifier Engineering Challenges
0 / 6 completedUninitialized Register
Investigate a program returning an uninitialized value. Correct the program and successfully attach it.
Packet Memory Boundaries
Investigate an unsafe packet read. Introduce a data_end check and verify the corrected program.
Nullable Map Pointer
Diagnose a map lookup result that is dereferenced without proving that the pointer is non-null.
Program Termination
Investigate an unbounded control-flow pattern. Replace it with a demonstrably bounded loop.
Helper Compatibility
Diagnose a helper that is incompatible with the selected program type and load a compatible example.
Kernel Portability
Investigate a CO-RE relocation failure, select a compatible target and enable the required relocation.
Successful verification is not a guarantee of correct application logic.
The eBPF verifier enforces important execution constraints, but a verified program can still implement incorrect policy, generate excessive telemetry or introduce operational overhead. BTF provides type information, while CO-RE uses relocation information and target type metadata to improve portability. Neither mechanism guarantees compatibility with every kernel, helper, attachment type or changed data structure.
eBPF Maps, Shared State and Event Communication
Engineering persistent kernel state, high-performance data lookups, distributed CPU counters, runtime policy tables and real-time communication between eBPF programs and userspace observability platforms.
Conceptual architecture showing three common map usage patterns: policy distribution, state aggregation and asynchronous event communication.
1. Why eBPF Maps Are Fundamental to Programmable Infrastructure
An eBPF program is typically invoked when an event occurs at its attachment point. That event could be an arriving packet, a system call, a scheduler operation or a security-sensitive kernel action.
Individual invocations need a mechanism for maintaining information beyond their immediate execution context.
BPF maps provide kernel-managed data objects that can retain state across program invocations, share information between compatible programs and communicate with authorised userspace components.
Persistent Runtime State
Maintain counters, timestamps, flow records and other information across separate events.
Dynamic Configuration
Allow a control agent to update supported policy and configuration data without recompiling the program for every change.
Information Exchange
Transfer aggregated measurements or individual event records between kernel instrumentation and userspace consumers.
Although many BPF maps provide key-value storage, specialised map types support event transport, program references, socket references, device redirection and other kernel integration mechanisms.
2. Anatomy of a BPF Map
A map is created with attributes appropriate to its selected map type.
Common attributes include the map type, key size, value size, maximum number of entries and map-specific flags.
Logical representation of a hash map. Actual memory allocation, hashing, bucket organisation and overhead depend on the kernel implementation.
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 4096);
__type(key, __u32);
__type(value, __u64);
} packet_counts SEC(".maps");
This declaration describes a hash map containing up to 4096 entries, with unsigned 32-bit keys and unsigned 64-bit values.
The example assumes the appropriate BPF and libbpf headers are included in the surrounding program.
3. Understanding the Major eBPF Map Types
Selecting a map type is an architectural decision. Different map implementations provide different lookup semantics, concurrency characteristics, memory requirements and operational behaviour.
Hash Maps
Dynamic key-value records for flows, identities, connection state and policy decisions.
Array Maps
Fixed indexed storage for counters, configuration values and predictable lookup patterns.
Per-CPU Maps
Separate CPU-local values that can reduce contention on frequently updated state.
LRU Hash Maps
Bounded dynamic storage with approximate least-recently-used eviction behaviour.
LPM Tries
Longest-prefix matching for address ranges, network classification and prefix policies.
Program Arrays
Store references to compatible BPF programs for supported tail-call execution.
Ring Buffers
Shared event transport from kernel producers to a userspace consumer.
Perf Event Arrays
Support perf-event-based communication and per-CPU event delivery arrangements.
Map-in-Map
Organise compatible inner maps through references held by an outer map.
4. Hash Maps and Runtime Policy Decisions
Hash maps are particularly useful when keys are not naturally represented by a small, contiguous index range.
A key could represent an IP address, process identifier, workload identity, network flow or a composite structure containing multiple classification fields.
Conceptual identity-based policy lookup. The selected attachment point and program logic determine how the returned policy is enforced.
__u32 identity = workload_id;
__u32 *policy =
bpf_map_lookup_elem(&policy_map, &identity);
if (!policy) {
/* Apply explicitly defined missing-key policy */
return DEFAULT_ACTION;
}
/* Translate stored policy into hook-specific action */
return policy_to_action(*policy);
The example is pseudocode. Identity derivation, default actions and return-value semantics depend on the actual security architecture and BPF program type.
A missing map entry must have deliberately defined behaviour. Engineers must distinguish between fail-open, fail-closed and other context-specific fallback strategies.
5. Array Maps and Predictable Indexed State
Array maps use integer indices to access a fixed collection of elements.
Unlike ordinary hash maps, array elements are preallocated and initially zeroed. Individual array entries cannot be removed using the ordinary map-delete operation.
Illustrative application-defined counter indices. These indices are not the numeric XDP action constants.
| Property | Hash map | Array map |
|---|---|---|
| Key structure | Fixed-size arbitrary key data | 32-bit integer index |
| Entry creation | Dynamic insertion | Preallocated elements |
| Entry deletion | Supported | Not supported for individual elements |
| Missing element | Possible for an absent key | Invalid or out-of-range index |
| Typical usage | Flow state and policy tables | Counters and fixed configuration |
6. Per-CPU Maps and High-Performance Counters
Modern Linux systems execute workloads across multiple CPU cores.
If every CPU updates the same shared counter, contention and cache-coherence traffic can become significant at high event rates.
Per-CPU map variants provide separate values associated with individual CPUs. Ordinary BPF lookups into these maps access the current CPU's value.
Synthetic four-CPU example. Raw value payload excludes allocation overhead, alignment and other map metadata.
struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64);
} event_count SEC(".maps");
Userspace can retrieve the per-CPU values and aggregate them into a system-wide measurement.
Userspace allocation must account for the number of possible CPUs and the required per-value alignment, rather than assuming that the number of currently online CPUs is sufficient.
Per-CPU values can reduce cross-CPU contention, but memory requirements grow with CPU count. Aggregation also introduces additional work and does not inherently provide a simultaneous, globally atomic snapshot.
7. LRU Maps and Dynamic Flow-State Retention
Runtime monitoring systems may encounter a continuously changing collection of network connections, processes and workload identities.
Retaining every observed object indefinitely is not practical. LRU hash maps provide bounded storage with eviction behaviour when capacity pressure occurs.
Before New Flow
| Flow | Recency |
|---|---|
| F101 | Recent |
| F205 | Recent |
| F309 | Older |
| F412 | Eviction candidate |
After New Flow
| Flow | State |
|---|---|
| F101 | Retained |
| F205 | Retained |
| F309 | Retained |
| F513 | New entry |
Illustrative eviction outcome. Linux BPF LRU implementations use approximate recency tracking; the exact eviction victim is not guaranteed by this simplified model.
LRU maps can be useful for temporary flow statistics and bounded caches.
However, eviction can remove information that a later operation expects to retrieve. Applications must therefore define how missing or evicted state is handled.
Avoid relying on approximate LRU eviction as the sole mechanism for expiring mandatory authorisation state. Security-critical state may require explicit expiry, validation and carefully controlled capacity behaviour.
8. LPM Tries and Longest-Prefix Matching
Longest-prefix matching is familiar to network engineers through IP routing tables.
BPF LPM trie maps provide a mechanism for matching keys against stored prefixes. They can be used to implement address classification, network policy tables and other prefix-based decisions.
Logical prefix hierarchy rather than the exact internal Linux trie implementation.
| Prefix | Stored classification | Matches 10.20.30.45? |
|---|---|---|
| 0.0.0.0/0 | Default | Yes |
| 10.0.0.0/8 | Internal network | Yes |
| 10.20.0.0/16 | Application environment | Yes |
| 10.20.30.0/24 | Protected service segment | Selected longest match |
struct ipv4_lpm_key {
__u32 prefixlen;
__u8 address[4];
};
struct {
__uint(type, BPF_MAP_TYPE_LPM_TRIE);
__uint(max_entries, 4096);
__uint(map_flags, BPF_F_NO_PREALLOC);
__type(key, struct ipv4_lpm_key);
__type(value, __u32);
} prefix_policy SEC(".maps");
The lookup key for a complete IPv4 address normally specifies a prefix length of 32, with address bytes represented in the appropriate network-byte ordering.
The map provides prefix lookup semantics. Route selection, next-hop resolution, packet forwarding and security enforcement require additional program logic or integration with other kernel facilities.
9. Program Arrays, Tail Calls and Map-in-Map Structures
Large BPF systems may organise functionality across multiple programs and data structures rather than implementing every operation inside a single program.
Program arrays allow compatible programs to be referenced by indexed entries and invoked through supported tail-call mechanisms.
A successful BPF tail call transfers execution to the target program and does not return to the original program.
If the tail call cannot be performed, execution continues in the original program after the helper call. Engineers must explicitly design the fallback path.
bpf_tail_call(ctx, &program_array, 1); /* * Reached only if the tail call * did not transfer execution. */ return FALLBACK_ACTION;
Map-in-Map Architecture
Array-of-maps and hash-of-maps structures allow an outer map to reference compatible inner maps.
A controller can prepare a compatible inner map and replace an outer-map reference rather than modifying every active policy entry individually.
This can support coherent policy-generation changes for readers using a single selected inner map. It does not automatically provide a transaction spanning multiple maps, multiple lookups or multiple hosts.
10. Ring Buffers and Kernel-to-Userspace Event Streaming
Reading aggregated counters is useful for measuring system behaviour, but security investigations often require individual event records.
A process execution event might contain a timestamp, process identifiers, executable information and other context relevant to the selected instrumentation point.
BPF ring buffers provide a shared multi-producer, single-consumer event transport mechanism.
Conceptual ring representation. Real BPF ring buffers use variable-length records, producer and consumer positions, record metadata and synchronisation.
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 1 << 20);
} events SEC(".maps");
For a BPF ring buffer, max_entries represents the data-area capacity in bytes rather than the number of key-value elements.
The capacity must satisfy the kernel's ring-buffer sizing requirements, including power-of-two and page-alignment constraints.
11. Event Reservation, Publication and Consumption
One common event-publication pattern reserves space in the ring buffer, initialises the event record and submits the completed record.
If reservation fails, the program must handle that condition appropriately.
Representative application record, excluding ring-buffer transport metadata and alignment overhead.
struct event {
__u64 timestamp;
__u32 tgid;
__u32 tid;
char comm[16];
};
/* Inside a compatible tracing program */
struct event *e;
e = bpf_ringbuf_reserve(
&events, sizeof(*e), 0);
if (!e) {
/* Record reservation failure if possible */
return 0;
}
__u64 ids = bpf_get_current_pid_tgid();
e->timestamp = bpf_ktime_get_ns();
e->tgid = ids >> 32;
e->tid = (__u32)ids;
bpf_get_current_comm(
e->comm, sizeof(e->comm));
bpf_ringbuf_submit(e, 0);
return 0;
This fragment assumes a compatible tracing program, the previously declared ring-buffer map and the necessary headers.
The timestamp is a monotonic kernel time measurement, not a directly formatted wall-clock timestamp.
The command name is not necessarily the full executable path or complete command line. Richer attribution requires additional instrumentation and context.
Production systems should define event versions, record sizes, field meanings, time representation and compatibility behaviour between kernel producers and userspace consumers.
12. Ring Buffers versus Perf Buffers
Perf-event-based buffers have historically been widely used for BPF event delivery.
BPF ring buffers provide an alternative architecture that can share capacity across producers and preserve reservation ordering within a single ring.
| Property | BPF ring buffer | Typical perf buffer |
|---|---|---|
| Capacity organisation | Shared within one ring | Separate per-CPU buffers |
| Producer architecture | Multiple producers | CPU-associated event delivery |
| Ordering | Reservation order within one ring | Per-buffer order; cross-CPU merging required |
| Memory utilisation | Shared capacity can absorb uneven CPU activity | Capacity allocated to individual buffers |
| Contention | Shared producer coordination | Can benefit from CPU-local separation |
| Failure handling | Track failed reservations or output operations | Track output failures and lost-event notifications |
| Compatibility | Requires ring-buffer support | Useful across a broader range of older kernels |
Reservation ordering within a ring buffer does not automatically establish the exact real-world chronological order of all operations across CPUs, processes or hosts. Timestamping and correlation remain important.
13. Atomic Operations, Synchronisation and Consistency
Multiple BPF program invocations may access shared map values concurrently.
Consider two CPUs incrementing the same ordinary shared counter using separate read, modify and write operations.
Atomic operations can prevent this particular lost-update problem when applied to a suitable shared counter.
__u64 *count =
bpf_map_lookup_elem(&counts, &key);
if (count)
__sync_fetch_and_add(count, 1);
Atomic instruction support, operand size, alignment and verifier acceptance depend on the target environment.
Atomic Operations
Coordinate supported updates to individual shared values without a separate read-modify-write race.
BPF Spin Locks
Protect supported map-value critical sections where the program type and verifier rules permit their use.
Per-CPU State
Reduce cross-CPU contention by maintaining separate values and aggregating later.
An atomic increment protects that operation. It does not automatically guarantee consistency across multiple fields, multiple entries or multiple map objects.
14. Map Pinning, Permissions and Policy Ownership
BPF maps are kernel objects with reference-counted lifetimes.
Supported maps can be pinned in the BPF filesystem so that authorised processes can obtain references independently of the original creating process.
A production security architecture should distinguish between components that require permission to change policy and components that only need to read measurements.
Relevant controls can include filesystem permissions, restricted file-descriptor access, map-specific flags, supported map freezing and kernel security mechanisms.
Map freezing restricts subsequent userspace modification through the applicable interfaces. It does not by itself prevent all modifications from BPF programs.
# Enumerate loaded maps sudo bpftool map show # Inspect one map sudo bpftool map show id 42 # Dump supported map contents sudo bpftool map dump id 42 # Inspect pinned objects sudo ls -l /sys/fs/bpf # Machine-readable map metadata sudo bpftool -j map show
Map ID 42 is illustrative. Dumping map contents may expose sensitive operational or security information and can introduce overhead on large or frequently updated maps.
15. Map Memory Consumption and Telemetry Capacity
Map capacity must be designed around expected workload cardinality, CPU count, event rates and the available kernel memory budget.
Raw value payload: 4096 keys × 64 CPUs × 64 bytes = 16,777,216 bytes = 16 MiB Additional memory may include: - Key storage - Hash table structures - Allocation metadata - Alignment and padding - Map implementation overhead
Event Streaming Capacity
Consider a telemetry producer generating 100,000 records per second, each with a 128-byte application payload.
The transport must accommodate additional record metadata and alignment overhead. Userspace must also decode, enrich and export the resulting event stream.
A large ring buffer can absorb temporary bursts, but it cannot compensate indefinitely for a consumer that processes events more slowly than producers generate them.
Sustainable event delivery requires the long-term consumer processing rate to accommodate the accepted producer rate. Buffer capacity primarily determines how much temporary imbalance can be absorbed.
16. Backpressure, Event Loss and Telemetry Integrity
Runtime observability is a multi-stage data pipeline.
An event may be captured successfully at the kernel hook but subsequently lost because of transport pressure, userspace queue exhaustion or downstream export failures.
Synthetic accounting example for a completed event cohort with no remaining in-flight records. Total delivery: 95%. Total loss: 5%.
| Telemetry stage | Important measurement | Engineering interpretation |
|---|---|---|
| Kernel hook | Invocation and attempted event counts | Establish the observed event workload. |
| Ring buffer | Reservation failures and occupancy estimates | Identify transport pressure. |
| Userspace reader | Consumption rate and processing delay | Identify slow consumers. |
| Processing queue | Queue depth and dropped records | Identify enrichment or processing bottlenecks. |
| Exporter | Retries, errors and acknowledged records | Identify downstream delivery problems. |
| Storage platform | Ingestion and indexing availability | Confirm evidence is available for investigation. |
A missing security event may indicate that an operation never occurred, but it may also indicate instrumentation gaps, event loss or downstream processing failure. Telemetry integrity must be monitored.
17. Why Is the Runtime Security Platform Missing Events?
Consider a Kubernetes runtime security deployment in which a node-level eBPF agent observes a substantial increase in process execution activity.
All required BPF programs remain loaded and attached, but the central security platform reports fewer events than expected.
Kernel Data Plane
Userspace Processing
Synthetic incident metrics, not measurements from a real deployment. Buffer occupancy represents an illustrative sampled estimate.
Central event counts no longer match the workload activity observed by independent monitoring sources.
Program and attachment inspection indicates that the expected kernel hooks are still active.
Application-maintained failure counters identify loss before events reach userspace.
Event decoding and enrichment cannot keep pace with kernel event production.
The producer attempts 120,000 events per second while the consumer processes approximately 90,000.
Evaluate CPU allocation, event enrichment cost, supported pipeline parallelism and appropriate buffer sizing.
Confirm reservation failures decrease, consumer throughput accommodates the workload and required events reach the central platform.
# Inspect loaded BPF programs sudo bpftool prog show # Inspect BPF maps and metadata sudo bpftool map show # Inspect supported attachment objects sudo bpftool link show # Inspect node CPU pressure cat /proc/pressure/cpu # Inspect Kubernetes resource usage kubectl top pods -n SECURITY_NAMESPACE # Inspect the affected agent's logs kubectl logs -n SECURITY_NAMESPACE AGENT_POD # Review deployment configuration kubectl get daemonset -n SECURITY_NAMESPACE
Namespace and pod names are placeholders. Kubernetes resource metrics require the appropriate metrics infrastructure.
Ring-buffer reservation failure counters and detailed processing metrics must be exposed by the actual instrumentation or agent. They are not automatically available from every bpftool inspection.
Sampling and filtering can reduce telemetry volume, but changes to security-sensitive event coverage must be governed by explicit detection requirements. Enforcement decisions and observability delivery should also be treated as separate architectural concerns.
18. Selecting the Right Map for the Engineering Requirement
| Engineering requirement | Candidate map type | Design consideration |
|---|---|---|
| Fixed configuration values | Array | Stable indices and controlled updates. |
| Identity-based security policy | Hash | Missing-key behaviour and policy ownership. |
| High-frequency packet counters | Per-CPU array | CPU count and aggregation cost. |
| Dynamic per-flow statistics | Hash or per-CPU hash | Flow cardinality and memory budget. |
| Bounded temporary flow cache | LRU hash | Eviction behaviour and missing state. |
| Network prefix classification | LPM trie | Prefix representation and policy semantics. |
| Modular program dispatch | Program array | Program compatibility and fallback paths. |
| Versioned policy replacement | Map-in-map | Inner-map compatibility and lifecycle. |
| Individual runtime event delivery | Ring buffer | Capacity, ordering and loss monitoring. |
| Compatible per-CPU event transport | Perf event array | Per-CPU capacity and event correlation. |
These are representative starting points. Actual map selection must account for supported kernel features, attachment context, workload behaviour and the security properties required by the complete application.
The Data Infrastructure Behind Programmable Kernel Intelligence
eBPF maps transform individual kernel program invocations into stateful infrastructure capabilities.
Hash maps provide dynamic lookup state. Array maps provide indexed storage. Per-CPU maps support scalable counters. LPM tries enable prefix classification. Program arrays support modular execution, while ring buffers and perf-event-based mechanisms deliver runtime evidence to userspace.
Production engineering requires careful attention to concurrency, memory capacity, policy ownership, object lifetime, event delivery and telemetry integrity.
Observe the event. Maintain the required state. Evaluate the policy. Publish the evidence. Validate the entire delivery pipeline.
Kernel Packet Processing Explorer
Investigate the programmable Linux networking datapath. Follow packets through network hardware, XDP, socket buffer allocation, Traffic Control and the kernel protocol stack. Compare early packet decisions, forwarding behaviour and illustrative processing costs.
Linux Kernel Datapath Cutaway
PACKET INTELLIGENCE ENGINENative XDP
Native XDP executes in a supporting network driver before the conventional socket buffer path, allowing early packet decisions.
Packet Header Inspection
| Source IP | 192.0.2.10 |
|---|---|
| Destination IP | 198.51.100.20 |
| Destination port | 443 |
| Frame length | 512 bytes |
| Classification | Trusted |
| Last completed outcome | — |
XDP programs must establish valid packet boundaries before reading headers. This laboratory represents a truncated frame as an explicit classification, not as a real packet-memory access.
Packet Decision Console
Datapath Processing Counters
Native XDP can reject suitable traffic before the conventional skb allocation path. Generic XDP executes after skb creation, while supported hardware offload may make a decision before host processing.
Packet Outcome Distribution
| Host work units | 0 |
|---|---|
| NIC work units | 0 |
| Socket buffers created | 0 |
| Early drops before skb | 0 |
| Redirect failures | 0 |
Execution Architecture Performance Laboratory
NORMALIZED TEACHING MODELCompare identical traffic batches and equivalent denied-source filtering policies across four execution architectures. XDP modes filter at their respective XDP hooks. Traditional Linux filters at TC ingress. Lower host work units indicate less modeled host processing.
| Architecture | Host work | NIC work | skb count | Dropped | Delivered |
|---|
Work units are arbitrary educational weights, not CPU cycles, latency measurements, packets-per-second benchmarks or vendor performance claims. NIC processing is accounted for separately rather than treated as free computation. Unsupported architectures are excluded from comparisons.
Baseline versus Current Configuration
Capture a baseline and then change the execution architecture or filtering policy. Both configurations are evaluated using the currently selected batch size and traffic mixture.
| Metric | Baseline | Current |
|---|
Capture a baseline to begin comparing configurations.
Programmable Packet Actions
XDP and TC expose different program contexts and action semantics. An XDP transmit or redirect path does not necessarily traverse the conventional TC egress path.
Guided Packet Engineering Challenges
0 / 6 completedEarly Packet Rejection
Reject a blocked-source packet using Native XDP. Confirm that no socket buffer is created.
Generic XDP Comparison
Reject the same packet using Generic XDP and observe the socket buffer processing difference.
Hardware-Offloaded Filtering
Reject denied traffic on a compatible programmable NIC before host receive processing.
Redirect Failure Recovery
Observe a failed redirect, restore the target and verify successful modeled delivery.
Layered Security Enforcement
Allow DNS through XDP but reject it at TC ingress. Identify the final policy enforcement point.
Outbound Policy Investigation
Forward a transit packet through the kernel stack, observe an egress drop and correct the outbound policy.
Choose the attachment point according to the required packet context.
XDP is particularly useful for early packet filtering, redirection and high-performance receive-path processing. TC provides access to skb-based packet metadata and ingress or egress policy enforcement. Production architecture must account for driver support, hardware capabilities, program compatibility, map design, observability and interactions with the wider Linux networking stack.
eBPF Networking, XDP and Traffic Control
Engineering high-performance Linux packet processing, programmable network attachment points, early packet filtering, traffic classification, accelerated forwarding and kernel-level network security.
Simplified receive path for a supported native XDP deployment. Forwarded traffic follows additional routing and transmit paths. Generic XDP operates later, after an SKB already exists.
1. Why eBPF Changes Linux Networking
Traditional Linux networking provides a rich collection of protocol processing, routing, firewalling, traffic classification and socket delivery mechanisms.
eBPF extends this architecture by allowing verified programs to execute at supported networking attachment points.
Instead of requiring every packet to traverse an identical processing path, engineers can introduce programmable decisions at different stages of the network data plane.
Early Packet Processing
Inspect and classify incoming packets at an early receive-path attachment point, potentially before SKB construction.
Traffic Classification
Apply programmable decisions to SKB-based traffic at supported ingress and egress hooks.
Socket-Level Intelligence
Observe or influence supported socket operations, connection decisions and application-facing network behaviour.
XDP, TC, cgroup socket hooks, socket filters and tracing programs have different execution contexts, available helpers, packet representations and return-value semantics.
2. NIC Receive Queues, DMA, RSS and NAPI
Before an eBPF networking program executes, the physical network interface must receive and process the arriving Ethernet frame.
Modern network interfaces commonly support multiple receive queues. Receive Side Scaling can distribute traffic across those queues using a configurable packet-header hash.
Representative queue-to-CPU arrangement. Actual IRQ affinity, NAPI scheduling and queue mappings depend on the driver and host configuration.
DMA
Allows the NIC to transfer packet data into host memory using driver-managed receive buffers.
RSS
Distributes eligible network flows across hardware receive queues to support parallel packet processing.
NAPI
Coordinates driver polling and interrupt handling to process receive events efficiently under varying traffic loads.
Native XDP programs typically execute within this driver receive-processing environment, before the normal SKB-based network stack is entered.
3. Understanding xdp_buff, xdp_md and the Socket Buffer
A central distinction between native XDP and traditional Linux packet processing is the representation of packet data.
Native XDP operates on receive-buffer information represented internally through XDP-specific kernel structures. The BPF program accesses its supported context through the xdp_md interface.
Conceptual linear buffer representation. Multi-buffer XDP packets require additional handling beyond the directly accessible linear region. Diagram widths are not proportional to header lengths.
If native XDP returns XDP_PASS, the driver can construct or build an SKB for normal networking processing.
The Linux socket buffer, represented by struct sk_buff internally, contains packet references and metadata used throughout the conventional networking stack.
| Property | Native XDP context | SKB-based processing |
|---|---|---|
| BPF interface | struct xdp_md | struct __sk_buff for relevant BPF types |
| Typical location | Early driver receive processing | Normal Linux networking path |
| Packet metadata | Restricted XDP-specific context | Richer networking metadata |
| Primary advantage | Early processing and potential avoidance of SKB work | Integration with broader networking functionality |
| Typical application | Early filtering and redirection | Traffic policy, classification and modification |
4. XDP Native, Generic and Hardware-Offloaded Modes
XDP describes a programmable packet-processing interface rather than one universally identical execution environment.
Native XDP
Executes in a supporting network driver, normally before SKB construction. Commonly selected for high-performance host-based packet processing.
Generic XDP
Executes through the generic SKB-based receive path. Useful when native support is unavailable, but does not avoid initial SKB construction.
Hardware Offload
Executes supported programs on compatible NIC hardware. Available instructions, helpers and map capabilities depend on the offload implementation.
Do not assume that a successfully attached XDP program is operating in native mode. Verify the actual attachment mode, driver capabilities and required program features.
5. The Five XDP Actions
An XDP program returns an action that determines how the receive-processing environment should handle the packet.
| Action | Numeric value | Packet outcome |
|---|---|---|
| XDP_ABORTED | 0 | Discard with exception reporting behaviour. |
| XDP_DROP | 1 | Discard the packet at the XDP processing point. |
| XDP_PASS | 2 | Continue into the normal receive path. |
| XDP_TX | 3 | Transmit through the receiving interface. |
| XDP_REDIRECT | 4 | Attempt redirection to a target selected through supported helpers. |
Returning XDP_REDIRECT does not by itself guarantee successful delivery. The program must establish a valid redirect target, and the driver and downstream processing must support the selected operation.
XDP_TX sends the resulting packet back through the receiving interface. Correct addressing, header modification and forwarding semantics remain the responsibility of the application architecture.
6. Ethernet Header Parsing and Packet Bounds Checking
Network packets are untrusted input. An arriving frame may be truncated, malformed or contain a different protocol layout than expected.
BPF programs must establish that packet accesses remain within the accessible data boundaries.
SEC("xdp")
int inspect_ethernet(struct xdp_md *ctx)
{
void *data =
(void *)(long)ctx->data;
void *data_end =
(void *)(long)ctx->data_end;
struct ethhdr *eth = data;
if ((void *)(eth + 1) > data_end)
return XDP_DROP;
/*
* The Ethernet header is now
* within the validated region.
*/
return XDP_PASS;
}
This educational fragment assumes the appropriate Linux and libbpf headers. It demonstrates a bounds check before accessing an Ethernet header.
Production parsers must also account for relevant VLAN encapsulation, IPv4 header lengths, IPv6 extension headers, fragmentation and supported multi-buffer packet behaviour.
Helpers that adjust packet boundaries may invalidate previously established packet pointers. Programs must reload and revalidate the relevant pointers before subsequent direct packet access.
7. TC Ingress, TC Egress and the SKB Data Plane
Traffic Control provides another major attachment environment for programmable Linux networking.
Unlike native XDP, TC BPF programs operate on SKB-based packet representations. This provides access to a broader range of networking metadata and operations.
Simplified conventional software paths. Additional hooks, virtual devices, offloads and alternate forwarding paths can change the observed processing sequence.
TC Ingress
Classify incoming SKB traffic, apply supported security decisions, modify packet metadata or redirect traffic before subsequent network processing.
TC Egress
Apply supported classification and policy decisions to traffic leaving a network device before its normal transmit processing.
SEC("tc")
int classify_packet(struct __sk_buff *skb)
{
/*
* Inspect supported packet metadata
* or validated packet headers.
*/
return TC_ACT_OK;
}
The example represents a conventional TC direct-action program. TCX and other attachment mechanisms may use different attachment and action conventions.
BPF classification can participate in a traffic-management architecture, but queue scheduling, rate enforcement and shaping require the appropriate additional mechanisms and configuration.
8. XDP versus TC: Selecting the Correct Processing Point
| Engineering property | Native XDP | TC BPF |
|---|---|---|
| Execution location | Early driver receive path | SKB-based ingress or egress |
| Traffic direction | Receive-triggered processing | Ingress and egress attachment points |
| Packet context | xdp_md | __sk_buff |
| Early packet rejection | Strong architectural fit | Possible after SKB processing begins |
| Networking metadata | More restricted context | Richer SKB-related metadata |
| Packet redirection | Supported XDP redirect mechanisms | Supported SKB redirect mechanisms |
| Hardware dependency | Native support depends on driver | Software TC generally has broader device coverage |
| Typical design role | Early filtering and accelerated forwarding | Workload policy and richer traffic processing |
A production networking platform may combine both attachment points rather than selecting one exclusively.
XDP can handle early packet rejection or selected accelerated paths, while TC provides additional classification and policy processing for packets that enter the normal SKB data plane.
9. DEVMAP, CPUMAP and XSKMAP
XDP redirection can use specialised BPF map types to select different processing destinations.
DEVMAP
Supports redirecting packets toward selected network devices using compatible XDP forwarding mechanisms.
CPUMAP
Supports transferring packet processing to another CPU, potentially separating receive processing from subsequent work.
XSKMAP
Associates map entries with AF_XDP sockets for supported packet delivery into userspace processing applications.
Successful map lookup and action selection do not prove that a packet reached its intended destination. Monitor redirect failures, queue pressure and downstream delivery outcomes.
10. AF_XDP, UMEM and Shared Packet Rings
AF_XDP provides a Linux socket interface designed for high-performance packet processing in userspace.
Rather than delivering every selected packet through the conventional socket protocol-processing path, a supporting XDP program can redirect traffic to an AF_XDP socket.
Logical descriptor and buffer ownership model. Ring entries refer to packet-buffer locations; they do not represent four separate copies of every packet.
| Component | Producer | Purpose |
|---|---|---|
| UMEM | Registered by userspace | Memory region containing packet buffers. |
| Fill ring | Userspace | Provide available receive-buffer addresses. |
| RX ring | Kernel | Deliver received packet descriptors. |
| TX ring | Userspace | Submit packet descriptors for transmission. |
| Completion ring | Kernel | Return completed transmit-buffer addresses for reuse. |
Copy Mode and Zero-Copy Mode
AF_XDP can operate using copy-based packet transfer or supported zero-copy arrangements.
Zero-copy operation depends on the network driver, device, queue configuration and other compatibility requirements. It must not be assumed merely because an AF_XDP socket has been created.
Userspace must not reuse or modify a packet buffer while another component owns it for receive or transmit processing. Correct descriptor lifecycle management is fundamental to AF_XDP reliability.
11. Socket-Level eBPF Networking
Not every networking decision requires access to raw Ethernet frames.
Socket-related BPF attachment points provide additional opportunities to observe or influence network behaviour closer to applications.
Cgroup Socket Address Hooks
Evaluate supported operations such as connect or bind in the context of cgroup-associated applications.
Socket Operations
Observe and influence supported TCP socket lifecycle events and selected connection-related behaviour.
SOCKMAP and SOCKHASH
Store supported socket references and participate in compatible socket-level redirection architectures.
Socket Filters
Apply filtering decisions to traffic associated with a socket using the semantics of the relevant program type.
Socket-level enforcement and packet-level enforcement solve different problems. A connection hook can evaluate a supported application operation, whereas a packet hook evaluates traffic passing through its particular attachment location.
12. Combining XDP, TC and Socket Hooks in Kubernetes
Modern Kubernetes networking platforms can use multiple eBPF attachment points to implement service connectivity, workload policy, load balancing and network observability.
Representative multi-hook architecture. The map layer represents shared state, not an obligatory packet-processing stage. Actual attachment points depend on the networking platform and configuration.
Cilium is a prominent example of a cloud-native networking platform that uses eBPF for networking and security capabilities.
Its data plane can combine different hooks and map structures for workload policy, service handling, forwarding and observability. Optional XDP acceleration depends on the deployment and supported configuration.
Packet-level policy can control network communication, but it does not provide complete visibility into process execution, filesystem activity or privilege changes. Runtime security requires additional instrumentation and policy mechanisms.
13. Early Packet Filtering and Defence in Depth
Early packet filtering can reduce the amount of unwanted traffic entering more expensive host-processing paths.
A programmable XDP filter may evaluate packet characteristics, address classifications and supported state maintained in BPF maps.
Synthetic packet-accounting example. All packets are accounted for as 700,000 XDP drops, 30,000 TC drops and 270,000 packets continuing beyond TC.
Early filtering can reduce downstream packet-processing demand, but it does not remove traffic from the physical link before the host receives it.
Volumetric attacks that saturate upstream connectivity may require mitigation at network infrastructure or service-provider locations before traffic reaches the host.
Network admission, application identity, encryption, workload isolation, runtime enforcement and incident response remain separate but complementary security responsibilities.
14. Packet Rate, CPU Budget and Data Plane Scalability
Network throughput is commonly expressed in bits per second, but programmable packet-processing systems must also account for packets per second.
A workload containing many small packets can impose a significantly different processing burden from a workload carrying the same bit rate using larger packets.
Minimum Ethernet Frames
64-byte Ethernet frame plus 8 bytes of preamble/SFD and 12 bytes of interframe gap.
Standard Full-Size Frames
1518-byte untagged Ethernet frame plus 20 bytes of equivalent per-frame wire overhead.
Theoretical Ethernet line-rate calculations, not measured XDP performance benchmarks.
10 Gb/s Ethernet: Minimum frame wire occupancy: 64 + 8 + 12 = 84 bytes 10,000,000,000 / (84 × 8) = 14,880,952 packets/s Illustrative CPU processing budget: 4 dedicated cores × 3 GHz = 12 billion cycles/s 12 billion / 14.88 million ≈ 806 CPU cycles per packet This is an idealised aggregate budget. It excludes scheduling, memory stalls, driver overhead and other workloads.
Actual performance depends on packet distribution, CPU frequency, cache locality, NUMA placement, map access, driver capabilities, program complexity and competing system activity.
CPU Locality
Align receive processing with appropriate CPU and NUMA resources to reduce unnecessary cross-node memory access.
Map Contention
Evaluate whether frequently accessed shared state introduces synchronisation or cache-coherence costs.
Program Complexity
Measure the cost of parsing, lookup, modification and telemetry generation under realistic packet workloads.
15. Measuring the Programmable Network Data Plane
A network engineer investigating an eBPF-based data plane must distinguish between physical reception, driver processing, BPF decisions and subsequent packet delivery.
| Processing stage | Evidence source | Engineering question |
|---|---|---|
| Physical NIC | Interface and driver statistics | Are packets reaching the device? |
| Receive queues | Per-queue counters and driver metrics | Is traffic distributed evenly? |
| Native XDP | Program-maintained action counters | Which actions are being selected? |
| XDP redirect | Supported redirect tracepoints and error counters | Are redirect operations completing? |
| TC | Filter statistics and BPF counters | Is SKB traffic being classified or rejected? |
| Network stack | Protocol and routing diagnostics | Is traffic reaching the expected stack path? |
| Application | Socket and application telemetry | Did the intended service receive the traffic? |
# Inspect network interfaces and XDP details ip -details link show dev eth0 # Inspect interface counters ip -s link show dev eth0 # Inspect loaded BPF programs sudo bpftool prog show # Inspect network BPF attachments sudo bpftool net show # Inspect available BPF link objects sudo bpftool link show # Inspect driver information sudo ethtool -i eth0 # Inspect driver statistics sudo ethtool -S eth0 # Inspect receive/transmit channel configuration sudo ethtool -l eth0 # Inspect RSS indirection configuration sudo ethtool -x eth0 # Inspect conventional TC ingress filters sudo tc -s filter show dev eth0 ingress # Inspect conventional TC egress filters sudo tc -s filter show dev eth0 egress # Inspect available XDP tracepoints sudo bpftrace -l 'tracepoint:xdp:*'
Interface eth0 is a placeholder. Command availability and reported statistics depend on installed tools, privileges, kernel version, driver capabilities and attachment mechanism.
A conventional tcpdump capture may not observe packets discarded by native XDP before they enter the normal SKB path. The absence of packets in that capture does not prove that the NIC never received them.
16. Why Has Packet Loss Increased While Average CPU Remains Low?
Consider a high-performance Linux networking deployment with four receive queues and a native XDP program.
During a traffic increase, the application begins reporting intermittent packet loss. Average host CPU utilisation appears moderate, and the XDP program remains attached.
CPU Processing Distribution
Receive Queue Traffic Share
| Evidence | Observed value | Interpretation |
|---|---|---|
| NIC ingress | 3,200,000 packets/s | Offered receive workload. |
| Pre-XDP loss | 200,000 packets/s | Loss occurs before program execution. |
| XDP invocations | 3,000,000 packets/s | Packets reaching the XDP program. |
| XDP_PASS | 3,000,000 packets/s | No deliberate XDP rejection in this scenario. |
| XDP_DROP | 0 packets/s | Policy filtering is not the identified loss source. |
| RX queue 0 | 70% of offered traffic | Severe receive distribution imbalance. |
Synthetic incident with an idealised four-CPU processing model. Counter semantics must be validated on real hardware before performing equivalent packet accounting.
Packet delivery deteriorates as the offered traffic rate increases.
Program inspection confirms that the expected attachment remains present.
NIC and program counters indicate that some offered packets never reach the BPF program.
Queue-level evidence shows that 70% of offered traffic is directed toward a single processing lane.
One CPU is saturated despite moderate average utilisation across the four processing CPUs.
Review traffic entropy, queue configuration, IRQ affinity, NUMA placement and supported receive-distribution mechanisms.
Repeat the workload and compare queue distribution, per-CPU load, receive losses and application delivery measurements.
A dominant network flow may continue hashing to one receive queue. Changes to receive steering must consider flow ordering, hardware capabilities and the actual workload characteristics.
17. Common eBPF Networking Failure Scenarios
| Observed symptom | Possible cause | Investigation direction |
|---|---|---|
| XDP program cannot attach | Driver limitations or unsupported program features | Inspect kernel logs, driver capabilities and attachment mode. |
| Program rejected during loading | Verifier rejection | Inspect verifier output, pointer validation and helper compatibility. |
| Lower performance than expected | Generic rather than native execution | Confirm actual XDP attachment mode. |
| Packets absent from tcpdump | Early XDP drop or redirection | Inspect action counters and earlier observation points. |
| Redirect selected but delivery fails | Invalid target or downstream queue failure | Inspect map targets, redirect errors and device compatibility. |
| AF_XDP receive starvation | Insufficient available fill-ring buffers | Inspect descriptor ownership and buffer replenishment. |
| Uneven CPU utilisation | Receive queue or flow imbalance | Inspect RSS, IRQ affinity and per-queue statistics. |
| Unexpected policy decisions | Incorrect map contents or attachment context | Validate policy state, hook direction and program semantics. |
| Missing workload telemetry | Instrumentation gaps or event loss | Inspect hook coverage and telemetry delivery counters. |
Troubleshooting should begin by establishing the packet's actual processing path, rather than assuming that every packet traverses every configured BPF program.
18. Designing a Reliable Programmable Network Data Plane
Choose the Correct Hook
Select an attachment point that provides the required packet context, metadata and supported enforcement semantics.
Validate Platform Support
Test kernel, driver, helper, map and hardware capabilities before deploying the intended architecture.
Define Failure Behaviour
Specify the outcome of missing policy, failed redirects, unsupported features and other exceptional conditions.
Measure Every Stage
Correlate NIC, queue, BPF, network stack and application evidence.
Engineer for Scale
Account for packet rate, CPU locality, queue distribution, map contention and telemetry processing cost.
Control Lifecycle Changes
Validate program replacement, policy updates, rollback behaviour and compatibility during upgrades.
The Linux Kernel as a Programmable Network Data Plane
eBPF enables programmable network decisions across multiple Linux processing environments.
Native XDP provides an early receive-path execution point. TC provides richer SKB-based ingress and egress processing. Specialised redirect maps support alternate device, CPU and userspace destinations, while socket-related hooks bring selected networking decisions closer to applications.
Production success depends on understanding where programs execute, what packet representation they receive, which operations are supported and how failures are measured.
Receive the packet. Validate its boundaries. Evaluate the policy. Select the data path. Verify the delivery outcome.
Runtime Threat Investigation Simulator
Investigate Linux and container runtime activity using conceptual eBPF security telemetry. Correlate process execution, file access, network connections and credential changes to distinguish legitimate workload behaviour from suspicious runtime incidents.
Runtime Security Architecture
SIMULATED KERNEL TELEMETRYeBPF Security Programs
Kernel-attached programs collect selected runtime events and associated metadata for security analysis.
Runtime Process Tree
OBSERVED PROCESS LINEAGEweb-api · PID 1201
| Parent PID | 1 |
|---|---|
| Container | app-frontend |
| Observed UID | 1000 |
| Execution identity | application-service |
| Observed state | Running |
Kernel Security Event Console
The process tree and security console represent observed telemetry. Disabled sensors and lost events can create incomplete or stale runtime visibility.
Correlated Incident Timeline
0 eventsIncident Evidence Board
Collect relevant events from the timeline. A security signal becomes stronger when supported by independent event categories and consistent process identity.
Incident Classification
Kernel Sensor Telemetry Distribution
Process, file, network and credential sensors observe different aspects of workload behaviour. No individual event source provides a complete representation of every runtime incident.
Telemetry Pipeline Health
| Enabled sensor categories | 4 / 4 |
|---|---|
| Events delivered | 0 |
| Simulated buffer losses | 0 |
| Eligible event delivery | — |
| Application isolation | Inactive |
| Prevented scenario actions | 0 |
All sensor categories enabled
Sensor configuration is healthy in the teaching model. This does not guarantee complete production visibility.
Incident Investigation Readiness
0 / 5 objectivesGuided Security Engineering Investigations
0 / 7 completedEstablish a Runtime Baseline
Observe normal process, file and network activity. Verify that expected workload behaviour does not require containment.
Unexpected Child Process
Investigate an unexpected shell launched from an application process. Correlate its parent and subsequent runtime activity.
Sensitive File Access
Identify an unexpected file access operation and determine which workload identity initiated it.
Unexpected External Connection
Correlate an external connection with its originating process and application context.
Credential Change Investigation
Distinguish a requested credential operation from an observed successful identity change.
Multi-Stage Runtime Incident
Correlate several suspicious events, preserve evidence and contain the affected workload.
False Positive Investigation
Examine authorized maintenance activity. Distinguish legitimate administrative behaviour from an actual policy violation.
Runtime Security Attachment Points
| Observation domain | Example mechanism |
|---|---|
| Process execution | sched_process_exec tracepoint |
| System call activity | Syscall tracepoints |
| File operations | VFS tracing / BPF LSM hooks |
| Network connections | Socket tracing / cgroup hooks |
| Credential changes | Credential-related tracing hooks |
| Telemetry delivery | BPF ring buffer / perf buffer |
Detection and Enforcement Boundaries
Collect runtime evidence
Tracing programs can observe selected kernel events. Observation alone does not automatically prevent an operation from completing.
Correlate security signals
Security agents and analytics pipelines evaluate observed activity against workload context, configured policies and detection rules.
Apply supported security controls
Appropriate BPF LSM or other enforcement hooks can participate in security decisions. External response systems may also isolate workloads or stop processes. Capabilities depend on the attachment type and production configuration.
Runtime security is an evidence correlation problem.
A shell process, sensitive file access or external connection is not independently sufficient to establish compromise. Engineers must correlate process lineage, workload identity, authorization, operation results, expected behaviour and telemetry completeness before making incident response decisions.
eBPF Runtime Security and Threat Detection
Engineering continuous workload visibility, process execution monitoring, kernel-level security instrumentation, behavioural threat detection and evidence-driven incident investigation across Linux and cloud-native infrastructure.
Conceptual runtime security architecture. Observation programs and enforcement programs may execute at different hooks. Enforcement decisions occur at supported security attachment points rather than waiting for userspace alert processing.
1. What Is Runtime Security?
Runtime security focuses on the behaviour of applications, processes and infrastructure while they are actively executing.
Image scanning, configuration assessment and vulnerability management provide important information about potential security weaknesses. However, they do not necessarily reveal what a workload is doing at a particular moment.
Runtime security attempts to close this visibility gap by observing actual execution behaviour and, where supported, enforcing security policy during relevant operations.
Pre-Deployment Security
Assess software images, dependencies, infrastructure configuration and known vulnerabilities before deployment.
Runtime Observation
Monitor process execution, filesystem activity, network connections and selected kernel security events.
Runtime Enforcement
Apply supported policy decisions at appropriate execution or security attachment points.
A workload can pass a deployment-time security assessment and subsequently exhibit unexpected behaviour because of compromised credentials, application vulnerabilities, configuration changes or unauthorised operations.
2. Why the Linux Kernel Is a Valuable Observation Point
Applications depend on operating-system services to perform many important operations, including creating processes, accessing files and establishing network connections.
The Linux kernel therefore provides valuable observation points that can reveal activity across multiple applications and containerised workloads.
Kernel visibility is nevertheless bounded by the instrumentation that has been deployed. An eBPF program attached to a process execution tracepoint does not automatically observe every filesystem operation or application-level transaction.
Some application behaviour occurs entirely in userspace and requires additional instrumentation, application telemetry or suitable uprobes to become visible.
3. Observing System Call Entry and Exit
System call instrumentation can provide information about operations requested by a userspace process and their eventual results.
Simplified entry and exit observation. Internal kernel processing and security checks vary by operation and kernel version.
| System call family | Observation opportunity | Security interpretation |
|---|---|---|
| execve / execveat | Requested executable image | Unexpected application execution. |
| openat / openat2 | File-open requests and outcomes | Potential access to protected resources. |
| connect | Socket connection attempts | Unexpected network destinations. |
| setuid / setresuid | Requested identity changes | Credential transition investigation. |
| mount | Filesystem mount operations | Changes to filesystem exposure. |
| ptrace | Process inspection or control requests | Potentially sensitive cross-process activity. |
An entry event records that an operation was requested. Its result must be evaluated using suitable exit events or other authoritative evidence before concluding that access, execution or a state change actually succeeded.
4. Process Execution, Parentage and Behavioural Context
Process execution monitoring is one of the most important capabilities of runtime security platforms.
An executable name alone provides limited security context. The process's parent, workload identity, execution time, credentials and subsequent behaviour can substantially improve interpretation.
Illustrative process tree for a workload that does not normally launch shells. Shell execution can be legitimate in other workload contexts.
Process Identity
Capture the process identifier, executable information and relevant execution lifecycle context.
Parent Process
Establish the observed process lineage and determine which workload initiated the operation.
Execution Context
Associate process activity with credentials, namespaces, cgroups and available workload metadata.
Linux process creation and executable replacement are distinct operations. A successful exec operation replaces the executable image of an existing process rather than necessarily creating a new process identifier.
Process identifiers are reused. Security platforms should correlate activity using a sufficiently stable process identity, such as a host identity, PID and process start-time combination, with additional execution-generation context where needed.
5. Connecting Kernel Events to Containers and Kubernetes Workloads
Containers share the host kernel while using isolation and resource-management mechanisms such as namespaces and cgroups.
A kernel security event may initially identify a host process and its execution context rather than directly providing a Kubernetes namespace, deployment name or application owner.
| Identity component | Purpose |
|---|---|
| Host PID | Identify the process in the host PID namespace. |
| Namespace context | Understand process and resource isolation boundaries. |
| Cgroup context | Associate activity with a resource-management hierarchy. |
| Container ID | Associate the process with a container runtime object. |
| Pod UID | Identify a particular Kubernetes pod instance. |
| Workload owner | Associate the pod with its deployment or other controller. |
| Image digest | Identify the deployed image content where metadata is available. |
Short-lived containers, metadata cache delays and workload termination can introduce enrichment gaps. Preserve original kernel event context and explicitly represent unresolved workload identities.
6. Sensitive File Access and Filesystem Behaviour
Filesystem monitoring can reveal unexpected attempts to access protected configuration, credential material, application data and security-sensitive system resources.
File-Open Observation
Identify attempts to open relevant resources and correlate the operation with its result and process context.
File Modification
Monitor supported write, rename, unlink and other operations that may change protected resources.
Object-Level Context
Use available file or inode context to improve identification beyond raw userspace pathname strings.
Workload Policy
Evaluate whether a particular workload is expected to access the resource under the applicable security policy.
Relative paths, directory descriptors, mount namespaces, symbolic links, renamed files and existing file descriptors complicate pathname-based detection. A successful open also does not establish that file contents were subsequently read or transferred.
7. Connecting Network Activity to Process Identity
Conventional network monitoring often identifies communication using addresses, ports, protocols and traffic volumes.
Runtime instrumentation can provide additional context by associating supported network operations with the processes and workloads responsible for them.
Synthetic workload example using a documentation-only external IP address. An unexpected destination is an investigation signal, not proof of malicious communication.
Connection telemetry can reveal the requested destination and operation outcome, but additional evidence may be required to establish whether a connection completed, whether application data was exchanged and what that data contained.
Observing an encrypted connection does not automatically expose its plaintext application payload. Network metadata, application telemetry and supported userspace instrumentation provide different visibility boundaries.
8. Monitoring Privilege and Credential Changes
Linux security decisions depend on multiple forms of process identity and authority, including user and group identifiers, capabilities, namespace context and security module policy.
| Observed transition | Security investigation |
|---|---|
| Effective UID change | Was the transition expected and permitted? |
| Capability-set change | Did the process gain or lose relevant authority? |
| Executable replacement | Did execution alter the process credential state? |
| Namespace transition | Did the operation change an isolation context? |
| Security policy denial | Which policy and operation produced the denial? |
The security implications of UID 0 depend on namespace mappings, capability scope, container configuration and other isolation controls. A credential transition must be interpreted within its actual execution context.
9. BPF LSM and Kernel-Level Security Decisions
The Linux Security Modules framework provides security hooks within the Linux kernel.
On appropriately configured kernels, BPF LSM enables supported eBPF programs to participate in security decisions at eligible LSM attachment points.
SEC("lsm/file_open")
int BPF_PROG(check_file_open,
struct file *file,
int ret)
{
/* Preserve an existing denial. */
if (ret != 0)
return ret;
/*
* Evaluate supported file context
* against configured security policy.
*
* A policy violation could return
* an appropriate negative error.
*/
return 0;
}
This educational fragment illustrates a conventional BPF LSM return pattern. It requires appropriate headers, kernel configuration and a compatible loader. It does not implement an actual deny policy.
A tracing program attached to an observation hook cannot be assumed to block the operation it observes. Enforcement requires an attachment mechanism with the appropriate supported decision semantics.
10. Constructing a Runtime Security Event
A useful runtime security event contains enough context to support interpretation, correlation and subsequent investigation.
{
"event_type": "process_exec",
"timestamp": "2026-11-25T10:42:18.240Z",
"host": "worker-node-03",
"process": {
"host_pid": 18420,
"parent_pid": 18110,
"start_time_ns": 582001000000,
"executable": "/bin/sh",
"effective_uid": 1000
},
"workload": {
"namespace": "production",
"pod": "api-7f92",
"container": "api"
},
"operation_result": "success",
"detection": {
"rule": "unexpected_shell_execution",
"severity": "medium"
}
}
This is a vendor-neutral event schema, not the native output format of a particular security product.
Command arguments, file paths and application data may contain credentials or personal information. Production security telemetry should apply appropriate filtering, redaction, access controls and retention limits.
11. Security Event Transport and Event Loss
Runtime security programs frequently generate events that must be transferred from kernel execution contexts into userspace security agents.
Depending on the implementation, this may use BPF ring buffers or supported perf event transport mechanisms.
Synthetic event accounting example. Successfully submitted events may still encounter downstream processing or export failures.
A security agent must be able to distinguish a quiet workload from a workload whose security events are not being successfully collected.
Monitor failed event reservations, consumer lag, userspace processing queues, export failures and sensor availability. Absence of an alert does not establish absence of suspicious activity.
12. From Individual Events to Behavioural Threat Detection
Individual runtime events often have legitimate explanations.
Behavioural detection improves security interpretation by evaluating activity against workload expectations and correlating related events over time.
Rule-Based Detection
Match observed activity against explicitly defined security conditions and workload policies.
Behavioural Baselines
Compare observed execution and communication patterns with established workload expectations.
Event Correlation
Combine process, filesystem, network and credential evidence associated with a common security context.
| Detection signal | Context | Possible interpretation |
|---|---|---|
| Unexpected shell | Application normally launches no shells | Unexpected execution requiring review. |
| Protected file access | Resource outside workload expectations | Potential unauthorised resource access. |
| New network destination | Destination absent from approved baseline | Unexpected external communication. |
| Credential transition | Identity change outside normal lifecycle | Potential privilege-related security event. |
| Multiple related signals | Shared process lineage and time window | Higher-priority investigation candidate. |
Detection quality depends on the programs, event schemas, policy definitions, correlation logic and investigation processes built around the instrumentation.
13. Correlating Process, File and Network Evidence
A correlation engine should preserve the relationship between an alert and its underlying observations.
Analysts need to understand which events were directly observed, which identities were enriched, which conclusions were inferred and which evidence remains unavailable.
Temporal Correlation
Associate related activity within an appropriate time window while accounting for event delivery delay and clock differences.
Entity Correlation
Associate events using stable process, host and workload identities rather than relying exclusively on executable names or IP addresses.
14. Tetragon, Falco and Cilium Hubble
Several cloud-native projects use kernel instrumentation or related networking mechanisms to provide security and observability capabilities.
Their architectural roles overlap in some areas, but they should not be treated as interchangeable products.
Tetragon
eBPF-based runtime security observability and supported enforcement capabilities, including process and workload activity monitored through tracing policies.
Falco
Runtime threat detection using supported event sources and a rule-based detection engine. Response integrations can consume its generated alerts.
Hubble
Network and security observability associated with the Cilium data plane, providing visibility into supported network flows and policy verdicts.
| Capability | Tetragon | Falco | Hubble |
|---|---|---|---|
| Process execution monitoring | Core capability | Supported through event sources and rules | Not its primary role |
| Filesystem activity | Supported through suitable instrumentation | Supported through relevant event sources | Not its primary role |
| Network flow visibility | Selected process-aware network activity | Relevant runtime network events | Core capability |
| Runtime enforcement | Supported policy actions and mechanisms | Detection-first; external response integrations | Observes Cilium networking policy outcomes |
| Kubernetes context | Workload-aware security context | Available metadata enrichment | Cilium workload and network identity context |
A production architecture may combine network observability, runtime event detection and kernel enforcement. Exact features, supported hooks and response capabilities depend on product versions and configuration.
15. Investigating Unexpected Behaviour in a Kubernetes API Workload
Consider a production API workload whose expected behaviour consists of processing application requests, accessing an internal database and communicating with approved services.
A runtime security sensor reports unexpected process execution followed by unusual filesystem and network activity.
Workload Identity
Namespace: production
Pod: api-7f92
Container: api
Node: worker-node-03
Effective UID: 1000
Investigation State
Process execution: OBSERVED
File-open result: DENIED
Network request: OBSERVED
Data transfer: UNVERIFIED
Compromise: UNCONFIRMED
| Relative time | Observation | Result | Interpretation |
|---|---|---|---|
| +0.0s | Unexpected shell execution | Successful exec | Outside workload baseline. |
| +1.2s | Protected file-open request | Permission denied | Attempt observed; access not established. |
| +3.6s | Unexpected outbound connection request | Completion unknown | Requires network evidence. |
| +4.8s | Observed process exit | Exit recorded | Process lifecycle ended. |
Synthetic defensive investigation. The observations support a security hypothesis but do not establish an attack, successful data access or data exfiltration.
Confirm the executable, process identity, parentage and workload context associated with the event.
Review expected application behaviour, recent deployments and authorised operational activity.
Determine which operation was requested and verify that the recorded result indicates denial.
Review available flow telemetry, connection outcomes and applicable network policy verdicts.
Determine whether event loss, missing hooks or enrichment gaps could affect the available evidence.
Preserve relevant evidence and follow established containment, escalation and recovery procedures appropriate to the confirmed risk.
An analyst must distinguish observed behaviour from inferred intent. Multiple unusual events justify investigation, but conclusions should remain proportional to the available evidence.
16. Linux CLI and Security Sensor Inspection
Engineers need to verify that the expected instrumentation is present, that relevant kernel features are available and that the security agent is operating correctly.
# Inspect the running kernel
uname -r
# Inspect available BPF capabilities
sudo bpftool feature probe kernel
# Inspect loaded BPF programs
sudo bpftool prog show
# Inspect BPF maps
sudo bpftool map show
# Inspect available BPF link objects
sudo bpftool link show
# Inspect active Linux security modules
cat /sys/kernel/security/lsm
# Inspect process execution tracepoints
sudo bpftrace -l 'tracepoint:sched:sched_process_*'
# Inspect available syscall tracepoints
sudo bpftrace -l 'tracepoint:syscalls:sys_enter_*'
# Inspect process identity and parentage
ps -eo pid,ppid,user,comm
# Inspect a selected process's cgroup
cat /proc/18420/cgroup
# Inspect process credential information
grep -E '^(Uid|Gid|CapEff|NoNewPrivs):' \
/proc/18420/status
# Inspect Kubernetes workloads
kubectl get pods -A -o wide
# Inspect the selected workload
kubectl describe pod api-7f92 -n production
These are representative inspection commands. The process identifier and Kubernetes workload name are synthetic placeholders.
Availability depends on the installed tools, privileges, kernel configuration, mounted filesystems and Kubernetes access permissions.
A BPF program can exist in the kernel without providing the expected observation coverage. Verify its actual attachment mechanism and test event generation using authorised representative activity.
17. Security Sensor Performance and Visibility Engineering
Runtime security instrumentation introduces additional work into selected execution paths.
Its operational cost depends on event frequency, program complexity, map operations, captured data size, filtering decisions and userspace processing capacity.
Unfiltered Event Collection
High-volume collection creates substantial transport and downstream processing demand.
Policy-Scoped Collection
Selective collection can reduce telemetry volume when security coverage requirements permit.
Illustrative decimal byte-rate calculations. These figures exclude record alignment, transport overhead, enrichment, storage and compression. They are not measured security sensor benchmarks.
Instrumentation Scope
Attach programs where the required security context can be obtained without unnecessary duplication.
Kernel-Side Filtering
Reduce irrelevant event generation where appropriate without silently sacrificing required security coverage.
Bounded State
Monitor map capacity, state eviction and lifecycle cleanup to maintain predictable resource usage.
Consumer Capacity
Ensure userspace event consumers can process expected workload volumes and event bursts.
Security Health
Monitor sensor availability, attachment coverage, event loss and metadata enrichment quality.
Controlled Rollout
Evaluate policy changes and instrumentation overhead using representative workloads before wider production deployment.
18. Common Runtime Security Failure Scenarios
| Observed symptom | Possible cause | Investigation direction |
|---|---|---|
| No process execution events | Missing or incorrect attachment | Verify hook availability, attachment and event generation. |
| Missing short-lived processes | Event loss or lifecycle correlation gap | Inspect transport counters and process identity handling. |
| Unknown container identity | Metadata enrichment failure | Inspect runtime metadata and cgroup correlation. |
| Unexpected file access alerts | Incomplete pathname or policy context | Validate object identity, operation result and workload baseline. |
| Connection alerts without flow evidence | Attempted or incomplete connection | Correlate socket results and network telemetry. |
| Enforcement policy has no effect | Observation-only attachment or unsupported action | Validate enforcement mechanism and kernel capabilities. |
| Excessive security alerts | Overly broad rules or incomplete baselines | Review detection context and authorised workload behaviour. |
| Increased application latency | Instrumentation or processing overhead | Measure execution cost, event rates and resource contention. |
| Incorrect event ordering | Concurrent producers or clock differences | Inspect timestamps, clock domains and correlation assumptions. |
| Silent security monitoring failure | Agent, transport or export outage | Validate end-to-end sensor health and independent alert delivery. |
19. Building a Defence-in-Depth Runtime Security Platform
Complementary security responsibilities, not a literal sequential packet or system call processing pipeline.
Runtime security is most effective when integrated into a broader architecture that reduces opportunities for compromise, limits the authority of workloads and provides reliable mechanisms for investigating and responding to security incidents.
From Kernel Events to Runtime Security Intelligence
eBPF provides programmable observation and supported enforcement opportunities across important Linux execution and security boundaries.
Process monitoring, filesystem instrumentation, network context and credential visibility can be combined to construct a richer understanding of workload behaviour.
However, the value of this architecture depends on reliable instrumentation, accurate identity correlation, appropriate policy design, event delivery integrity and disciplined security investigation.
Observe the operation. Establish its context. Verify the outcome. Correlate the evidence. Apply the appropriate security response.
Kernel Telemetry Engineering Lab
Explore how eBPF instrumentation transforms kernel and application activity into actionable telemetry. Configure probes, investigate event pressure, tune sampling and balance observability fidelity against instrumentation and telemetry processing costs.
Programmable Telemetry Architecture
LABORATORY READYeBPF Telemetry Programs
Instrumentation programs select, aggregate or export observations from supported attachment points.
Awaiting workload
Configure instrumentation and advance the simulation.
Telemetry Throughput History
LAST 30 SIMULATED SECONDSHook invocations, sampled observations and exported records are different quantities. Aggregation can represent many observations using fewer records.
Ring Buffer Pressure History
Buffer empty
The modeled producer and consumer have not yet processed any records.
Instrumentation Event Distribution
| Attachment | Invocations/s | Selected/s |
|---|
Telemetry Accounting
| Total hook invocations | 0 |
|---|---|
| Selected observations | 0 |
| Excluded by sampling | 0 |
| Map aggregation updates | 0 |
| Export records produced | 0 |
| Export records delivered | 0 |
| Export records lost | 0 |
| Queued records | 0 |
| Record accounting balance | Balanced |
Produced export records equal delivered records, queued records and lost records in this simplified telemetry transport model.
CPU Profile Explorer
SYNTHETIC STACK SAMPLESCPU sampling
Enable performance events and advance the workload to generate an illustrative stack profile.
Horizontal width represents the relative number of modeled samples, not chronological execution time. The profile uses synthetic workload-specific stacks.
System Call Latency Histogram
0 observations| Approximate p50 | — |
|---|---|
| Approximate p95 | — |
| Approximate p99 | — |
This synthetic histogram represents selected, paired syscall entry and exit observations in the tracepoint model. Percentiles are approximated using histogram bucket upper bounds.
Baseline versus Current Telemetry
| Metric | Baseline | Current |
|---|
Capture a baseline, change one instrumentation or pipeline parameter, and compare the resulting throughput, queue pressure and modeled CPU cost. Keep workload intensity constant when isolating the effect of a configuration change.
Observability Engineering Console
Guided Observability Engineering Investigations
0 / 6 completedEstablish a Healthy Baseline
Deliver full-fidelity raw telemetry for five seconds without losing records or building a persistent queue.
Investigate Ring Buffer Pressure
Reproduce export record loss. Recover by increasing consumer capacity while preserving full event sampling.
Engineer a Sampling Strategy
Reduce retained event volume without disabling instrumentation. Preserve at least 25% of observations while preventing transport loss.
Move Aggregation into the Kernel
Replace high-volume raw export with map-based summaries while retaining all modeled observations.
Investigate Tail Latency
Observe a synthetic syscall latency incident. Compare p95 against the healthy baseline, then verify recovery.
Recover a Stalled Collector
Observe telemetry queue growth during a userspace collector stall. Restore consumption and drain the backlog.
No active investigation
Select a guided investigation to configure a reproducible observability engineering experiment.
Instrumentation Mechanism Comparison
| Mechanism | Observation target | Engineering consideration |
|---|---|---|
| Kprobe / kretprobe | Kernel functions | Kernel version and function availability |
| Uprobe / uretprobe | Userspace functions | Executable identity and symbol offsets |
| Tracepoint | Defined kernel events | Event availability and field compatibility |
| Perf event | Hardware or software events | Sampling frequency and profiling overhead |
| fentry / fexit | Supported kernel functions | BTF and trampoline support |
Production Observability Principles
Observe selectively
Attach programs to the events needed to answer a specific engineering question. Unnecessary high-frequency instrumentation can increase cost.
Reduce export amplification
BPF maps can maintain counters and histograms without exporting a separate record for every observed operation.
Measure what was lost
Monitor failed event reservations, collector capacity and downstream processing health. Missing telemetry can distort incident analysis.
More telemetry does not automatically mean better observability.
Effective observability requires appropriate attachment points, representative sampling, efficient aggregation, reliable event transport and sufficient userspace processing capacity. Engineers must understand the fidelity and cost of the resulting evidence.
eBPF Observability, Distributed Tracing and Performance Engineering
Engineering deep Linux infrastructure visibility through programmable kernel instrumentation, CPU profiling, scheduler analysis, application tracing, network performance telemetry and evidence-driven distributed system troubleshooting.
Conceptual observability architecture. The central eBPF processor graphic represents software instrumentation rather than dedicated physical hardware. Different programs may use different hooks, maps and transport mechanisms.
1. From Monitoring to Infrastructure Observability
Monitoring typically measures predefined infrastructure and application conditions. Observability extends this capability by helping engineers investigate internal system behaviour using available telemetry.
Traditional infrastructure monitoring can indicate that CPU utilisation has increased, network latency has deteriorated or application response times have exceeded their expected operating range.
The engineering challenge is determining why those conditions have changed. eBPF provides additional instrumentation opportunities across Linux execution paths, making it possible to examine behaviour beneath conventional application metrics.
Metrics
Numerical measurements of resource utilisation, event rates, latency distributions and system health.
Logs
Discrete records containing application, infrastructure or security event context.
Traces
Relationships between operations within a request or distributed execution journey.
Profiles
Statistical or measured representations of where execution time and other resources are consumed.
Useful observability requires relevant instrumentation, reliable collection, appropriate aggregation and sufficient context to investigate system behaviour. Additional data does not automatically produce additional understanding.
2. Kprobes, Uprobes, Tracepoints and Function Tracing
Linux provides multiple mechanisms through which eBPF programs can observe execution events.
Selecting an attachment mechanism requires understanding the required event context, kernel compatibility, instrumentation stability and expected execution overhead.
| Attachment mechanism | Observation boundary | Engineering consideration |
|---|---|---|
| Tracepoint | Defined kernel event | Often more stable than internal function instrumentation. |
| Kprobe | Supported kernel instruction or function location | Internal implementation details can change between kernels. |
| Kretprobe | Kernel function return | Useful for return values and suitable duration measurements. |
| Uprobe | Userspace executable or library location | Depends on binary layout, symbols and instrumentation context. |
| Uretprobe | Userspace function return | Useful for selected application function measurements. |
| USDT | Application-defined static probe | Requires suitable probes in the application or library. |
| Fentry / Fexit | Eligible kernel function entry or exit | Requires appropriate kernel, BTF and tracing support. |
| Perf event | Supported software or hardware event | Useful for statistical profiling and selected counters. |
A tracepoint may provide a suitable event contract, while a function probe may expose more specific internal behaviour. Neither mechanism is universally appropriate. Validate attachment availability and event semantics against the target kernel.
3. Understanding On-CPU Profiling
CPU utilisation indicates how much processing capacity is being consumed. CPU profiling investigates which execution paths are consuming it.
Statistical profiling periodically samples executing threads and attempts to capture their instruction or stack context. Aggregating these samples can reveal frequently executing functions.
Illustrative sampling timeline. The animated sweep represents the observation process, not live CPU measurements.
Sampling Frequency
Higher sampling frequencies may improve statistical detail but can increase instrumentation and processing cost.
Stack Collection
Capture supported userspace and kernel stack information to associate samples with execution paths.
Symbol Resolution
Resolve collected addresses into meaningful function names using available binary and kernel metadata.
4. Reading CPU Flame Graphs
Flame graphs aggregate stack samples into a visual representation of execution paths.
The horizontal width of a frame represents its contribution to the measured sample population. Vertical position represents stack depth.
Synthetic stack population. Frame widths are proportional to sample contribution. Colours are decorative and highlight an illustrative hot path; they do not encode an independent measured temperature or latency value.
In this example, the request-processing branch accounts for 60% of collected CPU samples, while the highlighted formatting function accounts for 25%.
Engineers can investigate whether serialization and formatting work represents a meaningful optimization opportunity.
Horizontal position does not generally represent the time at which a function executed. Parent-frame widths include descendant samples, so adding parent and child percentages can double-count the same execution samples.
5. Off-CPU Analysis and Scheduler Latency
Application latency can increase even when CPU utilisation remains relatively low.
A thread may be waiting for storage, network activity, a synchronization primitive or an opportunity to execute on an available CPU.
Synthetic single-thread example. Real distributed requests may involve overlapping operations, multiple threads and asynchronous execution.
Suitable scheduler tracepoints can help identify when a thread stops executing, becomes runnable and subsequently resumes execution.
| Measurement | Interpretation |
|---|---|
| On-CPU time | Time spent executing on a CPU. |
| Off-CPU time | Elapsed time during which the thread is not executing. |
| Blocked time | Time spent waiting in a non-runnable state. |
| Run queue latency | Time spent runnable before receiving CPU execution. |
| Context switches | Transitions between executing tasks. |
Aggregate utilisation can conceal per-core saturation, CPU affinity restrictions, cgroup CPU quotas and localized contention. Investigate the execution context of affected threads rather than relying exclusively on host-wide averages.
6. Measuring Function and Operation Duration
An eBPF program can record a timestamp at a suitable operation entry point and compare it with a timestamp collected at the corresponding completion point.
sudo bpftrace -e '
tracepoint:syscalls:sys_enter_read
{
@start[tid] = nsecs;
}
tracepoint:syscalls:sys_exit_read
/@start[tid]/
{
@latency_us =
hist((nsecs - @start[tid]) / 1000);
delete(@start[tid]);
}
END
{
clear(@start);
}'
This example measures elapsed time between selected read system call entry and exit tracepoints and aggregates the observed durations into a histogram.
The measurement includes time spent waiting during the system call. It does not isolate physical disk service time or CPU execution time. Required tracepoints and bpftrace syntax should be verified against the installed environment.
A thread identifier can be sufficient for selected non-nested operations. Recursive functions, asynchronous requests and overlapping operations may require richer correlation keys, nesting state or request identifiers. Missing completion events also require appropriate state cleanup.
7. Latency Histograms and Tail Latency
Average latency can conceal a small population of unusually slow operations.
Histograms preserve information about the distribution of observed durations, allowing engineers to investigate variability and tail latency.
Synthetic histogram with lower-inclusive, upper-exclusive duration buckets. Exact percentile values cannot generally be recovered from bucket counts alone.
P50 — Median
Represents the middle of the observed latency distribution.
P95 — Elevated Latency
Helps characterize slower operations beyond the typical request population.
P99 — Tail Latency
Helps investigate uncommon but potentially important slow operations.
Averaging P99 values across servers does not generally produce the global P99. Aggregate compatible histogram populations or use an appropriate distribution aggregation method before estimating fleet-wide percentiles.
8. Block I/O Latency and Storage Investigation
Application storage latency can originate from filesystem processing, page-cache behaviour, block-layer queueing, device service time or other execution delays.
Simplified buffered-read architecture. Direct I/O, readahead, asynchronous I/O, network filesystems and other storage mechanisms can follow different paths.
Application I/O Latency
Measure the elapsed time experienced by the application at a suitable operation boundary.
Block Request Latency
Observe durations between appropriate block-layer request events.
Queueing and Contention
Investigate whether outstanding requests, device saturation or resource contention contribute to increased latency.
The measured duration depends on the chosen start and completion events. Request merging, splitting, requeueing and asynchronous execution complicate attribution to individual application operations.
9. TCP Retransmissions, RTT and Connection Behaviour
eBPF instrumentation can provide visibility into supported TCP/IP stack events and socket state.
This allows engineers to investigate network performance from the host's perspective, complementing packet captures, switch telemetry and application-level measurements.
Conceptual TCP loss-recovery sequence. Actual retransmission triggers depend on TCP implementation, acknowledgements, timers and recovery algorithms.
| Network signal | Potential engineering insight |
|---|---|
| TCP retransmissions | Potential loss, reordering or delayed acknowledgement behaviour. |
| Smoothed RTT | Transport-layer round-trip time estimate. |
| Connection duration | Lifecycle characteristics of selected socket connections. |
| Connection establishment latency | Delay across an appropriately defined connection boundary. |
| Socket queue behaviour | Potential application consumption or transmission pressure. |
| TCP state transitions | Connection establishment, closure and lifecycle investigation. |
Retransmission telemetry indicates transport-layer recovery activity. Establishing the cause may require host interface counters, packet captures, network queue telemetry, routing information and evidence from both connection endpoints.
10. Distributed Tracing and Request Context Propagation
Modern applications frequently execute a single logical request across multiple services, processes and infrastructure components.
Distributed tracing associates related operations using trace identifiers, span identifiers and propagated request context.
Synthetic nested trace. Child spans overlap their parent spans, so their durations must not simply be added together to calculate request latency.
Trace Identifier
Associates spans belonging to a common distributed trace.
Span Identifier
Identifies an individual operation within the trace.
Context Propagation
Carries relevant trace context across supported application and communication boundaries.
eBPF can observe selected application functions, sockets and protocol activity. Reliable end-to-end tracing still requires appropriate context extraction, propagation or correlation. Encryption, multiplexed connections, asynchronous execution and unsupported protocols can limit automatic reconstruction.
11. Combining Application Traces with Kernel Evidence
Application tracing can identify a slow service operation without necessarily explaining the underlying operating-system behaviour.
Kernel telemetry provides additional evidence that may help investigate the cause of the delay.
A storage latency increase occurring during a slow application span is a useful investigation signal. Demonstrating causation requires appropriate workload attribution, operation-level evidence or controlled validation of the suspected dependency.
12. BPF Maps, Counters and Histograms
Exporting every observed kernel event into userspace can create substantial telemetry volume.
Kernel-side aggregation allows suitable eBPF programs to maintain counters, histograms and other bounded state within BPF maps.
Shared Maps
Maintain state accessible across relevant execution contexts, subject to map-specific concurrency requirements.
Per-CPU Maps
Maintain CPU-specific values, potentially reducing contention for suitable aggregation workloads.
Stack Trace Maps
Store supported stack information that can be associated with profiling sample counts.
Per-CPU values can reduce shared-state contention but may increase memory requirements. Userspace collection must aggregate the relevant CPU values, and a collection across multiple CPUs is not necessarily an atomic snapshot.
13. Exporting eBPF Metrics into Prometheus
eBPF maps and event streams do not automatically become Prometheus metrics.
A userspace exporter or observability agent must collect the relevant state, apply appropriate metric semantics and expose or deliver the resulting measurements.
# TYPE ebpf_tcp_retransmits_total counter
ebpf_tcp_retransmits_total{node="worker-03"} 420
# TYPE ebpf_read_duration_seconds histogram
ebpf_read_duration_seconds_bucket{le="0.001"} 100
ebpf_read_duration_seconds_bucket{le="0.002"} 500
ebpf_read_duration_seconds_bucket{le="0.004"} 800
ebpf_read_duration_seconds_bucket{le="0.008"} 920
ebpf_read_duration_seconds_bucket{le="0.016"} 970
ebpf_read_duration_seconds_bucket{le="0.032"} 990
ebpf_read_duration_seconds_bucket{le="0.064"} 1000
ebpf_read_duration_seconds_bucket{le="+Inf"} 1000
ebpf_read_duration_seconds_sum 3.42
ebpf_read_duration_seconds_count 1000
These metric names and values illustrate a hypothetical exporter. They are not guaranteed to exist in a particular observability product.
# TCP retransmission rate
rate(ebpf_tcp_retransmits_total[5m])
# Fleet-wide P99 estimate for compatible
# classic histogram buckets
histogram_quantile(
0.99,
sum by (le) (
rate(
ebpf_read_duration_seconds_bucket[5m]
)
)
)
# Mean observed read duration
sum(rate(ebpf_read_duration_seconds_sum[5m]))
/
sum(rate(ebpf_read_duration_seconds_count[5m]))
Prometheus classic histogram buckets are cumulative. Exporters must correctly translate underlying non-cumulative bucket counts, measurement units and counter lifecycle behaviour. Quantile estimates depend on the exported bucket boundaries.
14. OpenTelemetry, eBPF and Unified Observability
OpenTelemetry provides standards and components for generating, collecting, processing and exporting observability signals.
eBPF-based instrumentation can complement application SDKs and other telemetry sources, subject to the capabilities of the selected instrumentation and integration components.
Conceptual integration architecture. Signal support, receiver availability, profiling integration and exporter capabilities depend on the selected agent, collector distribution and version.
Application Context
SDK instrumentation can provide business-operation names, trace context and application-specific attributes.
Infrastructure Context
eBPF-based agents can provide supported execution, network and kernel performance measurements.
Resource Enrichment
Associate telemetry with available host, service, container and Kubernetes workload metadata.
15. Memory Allocation, Page Faults and Resource Pressure
Memory-related performance problems can originate from allocation overhead, page faults, reclaim activity, memory pressure and application allocation patterns.
Allocation Profiling
Observe selected allocation paths and stack contexts to investigate allocation frequency and size.
Page Faults
Investigate supported page fault events and their relationship to execution delays.
Memory Reclaim
Observe selected reclaim activity and correlate it with workload latency and memory pressure.
OOM Investigation
Correlate available out-of-memory events with cgroup limits, kernel logs and workload state.
NUMA Behaviour
Combine supported profiling measurements with CPU placement and memory locality information.
Pressure Stall Information
Use Linux PSI measurements alongside instrumentation to investigate resource-related stalls.
A workload may allocate large quantities of memory over time while maintaining a relatively small live allocation footprint. Leak investigation requires suitable allocation and release tracking, retention evidence and awareness of allocator behaviour.
16. Investigating a Microservice Latency Incident
Consider a production API service experiencing a substantial increase in tail latency following a period of otherwise stable operation.
Application tracing identifies a slow database dependency, but the application CPU utilisation remains below its usual saturation threshold.
| Measurement | Baseline | Incident | Interpretation |
|---|---|---|---|
| API P99 | 80 ms | 480 ms | Sixfold increase. |
| API host CPU | 35% | 38% | No clear host-wide CPU saturation. |
| Database block I/O P99 | 4 ms | 42 ms | Substantial storage-path latency increase. |
| Database worker off-CPU P95 | 12 ms | 95 ms | Increased thread waiting. |
| TCP retransmitted segment ratio | 0.2% | 0.2% | No increase in this selected network signal. |
Synthetic incident measurements. Storage contention is a leading investigation hypothesis rather than a confirmed root cause.
Confirm increased API tail latency and identify affected requests and workloads.
Identify slow database spans and establish the affected dependency.
Compare on-CPU profiles, blocked waiting and runnable scheduling delays for database workers.
Determine whether block request durations and queueing increased on the affected database host.
Correlate slow database operations with storage activity and examine independent device, database and infrastructure telemetry.
Following an authorised corrective action, compare request latency, storage distributions and workload behaviour with the original baseline.
17. Practical eBPF Performance Investigation Commands
Linux performance engineers can combine eBPF-based utilities with conventional operating-system tools to investigate infrastructure behaviour.
# Kernel and BPF capability inspection
uname -r
sudo bpftool feature probe kernel
# Inspect loaded programs and maps
sudo bpftool prog show
sudo bpftool map show
# Discover available scheduler events
sudo bpftrace -l 'tracepoint:sched:*'
# Discover available block-layer events
sudo bpftrace -l 'tracepoint:block:*'
# Discover available TCP events
sudo bpftrace -l 'tracepoint:tcp:*'
# Sample kernel stacks for 10 seconds
sudo bpftrace -e '
profile:hz:49
{
@[kstack] = count();
}
interval:s:10
{
exit();
}'
# Conventional Linux performance evidence
vmstat 1
iostat -xz 1
mpstat -P ALL 1
ss -ti
# Resource pressure information
cat /proc/pressure/cpu
cat /proc/pressure/memory
cat /proc/pressure/io
| BCC utility | Typical investigation purpose |
|---|---|
| profile | CPU stack sampling. |
| offcputime | Off-CPU stack and duration analysis. |
| runqlat | Scheduler run queue latency distributions. |
| biolatency | Block I/O latency histograms. |
| biosnoop | Selected block I/O event details. |
| tcpretrans | TCP retransmission observation. |
| tcplife | TCP connection lifecycle measurements. |
| funclatency | Selected function duration distributions. |
Tool names, installation paths, supported options and attachment mechanisms vary by distribution and BCC release. Some distributions install these utilities with a -bpfcc suffix.
Use appropriate privileges, representative sampling frequencies, bounded collection windows and controlled instrumentation scope. Measure the overhead of observability itself when investigating sensitive production workloads.
18. Telemetry Cardinality, Sampling and Resource Efficiency
An observability platform must balance measurement detail with CPU consumption, kernel memory usage, network bandwidth, backend ingestion capacity and storage cost.
Raw Event Export
Exporting each event preserves individual event detail but creates a high-volume pipeline.
Aggregated Metric Export
Exporting aggregated measurements can dramatically reduce raw payload volume for suitable metrics.
Illustrative payload arithmetic using decimal byte units. Actual export formats, labels, framing, compression and metadata change the resulting transport volume. Aggregated metrics do not preserve all raw event detail.
Kernel Filtering
Restrict instrumentation output to the workload and operation scope required by the investigation.
Sampling
Collect a representative subset where statistical measurements are appropriate.
Aggregation
Maintain counters and distributions without exporting every individual operation.
Cardinality Control
Avoid unbounded metric labels containing request identifiers, ephemeral process identifiers or arbitrary resource names.
Event Loss Monitoring
Track failed submissions, dropped records and downstream processing failures.
Collection Lifecycle
Manage program attachment, map cleanup, exporter availability and controlled configuration changes.
19. Common eBPF Observability Failure Scenarios
| Observed symptom | Possible explanation | Investigation direction |
|---|---|---|
| Empty CPU profile | Attachment or sampling failure | Verify perf event availability and target execution. |
| Unknown stack frames | Missing symbols or unwind limitations | Inspect binaries, symbol metadata and stack collection support. |
| Incorrect function duration | Entry and exit correlation mismatch | Review keys, nesting and temporary state lifecycle. |
| Missing network activity | Incorrect instrumentation boundary | Verify protocol, socket context and hook coverage. |
| Unexpected histogram values | Incorrect units or bucket conversion | Validate duration calculation and exporter semantics. |
| Incomplete distributed traces | Missing context propagation | Inspect application instrumentation and protocol support. |
| High exporter memory usage | Unbounded state or metric cardinality | Review label dimensions, map capacity and retention. |
| Telemetry gaps under load | Buffer exhaustion or consumer lag | Inspect event loss and processing capacity. |
| Inconsistent timestamps | Different clock domains | Validate monotonic-to-wall-clock conversion and synchronization. |
| Increased application overhead | Excessive instrumentation cost | Measure program execution, event frequency and collection overhead. |
20. Building a Production eBPF Observability Platform
Vendor-neutral reference architecture. Application instrumentation and other infrastructure telemetry sources can feed the collection layer independently. Node-agent deployment requires appropriate security controls and kernel compatibility.
Controlled Instrumentation
Maintain approved program versions, supported attachment points and documented observation coverage.
Node-Level Collection
Collect supported telemetry close to the workload execution boundary.
Workload Attribution
Associate measurements with relevant service, process, container and infrastructure identities.
Observability Governance
Apply appropriate privileges, data filtering, retention and tenant access restrictions.
Pipeline Reliability
Monitor collection availability, event loss, export failures and backend ingestion health.
Engineering Validation
Compare baseline and incident measurements, validate hypotheses and verify recovery after changes.
From Infrastructure Telemetry to Performance Understanding
eBPF provides powerful instrumentation opportunities across Linux application and kernel execution boundaries.
CPU profiling reveals frequently executing code paths. Scheduler instrumentation helps distinguish execution from waiting. Storage and network telemetry expose selected infrastructure performance conditions.
When these measurements are combined with application traces, reliable workload identity and disciplined investigation methods, engineers can develop a more complete understanding of distributed system behaviour.
Measure the symptom. Identify the execution boundary. Examine the latency distribution. Correlate independent evidence. Validate the performance hypothesis.
Kubernetes Security Investigation Centre
Investigate security incidents across a distributed Kubernetes cluster. Correlate network flows, process execution events, runtime alerts and workload identities to establish evidence, identify affected workloads and validate incident containment.
Distributed Kubernetes Security Architecture
CLUSTER READYKubernetes Security Architecture
Select a workload, network boundary or security technology to inspect its role in the investigation.
Cilium / Hubble
0Observe network flows, workload identities, destinations and forwarding or drop verdicts.
ONLINETetragon
0Observe process execution and selected kernel events according to configured tracing policies.
ONLINEFalco
0Evaluate supported runtime events against configured security detection rules and generate alerts.
ONLINEHubble Network Flow Explorer
SYNTHETIC FLOW RECORDS| Time | Source | Destination | Protocol | Verdict |
|---|
A forwarded flow establishes that communication was observed at the modeled network observation point. It does not independently prove malicious intent.
Runtime Process and Alert Console
CORRELATED SECURITY EVENTSCross-Source Evidence Collection
Incident Evidence Board
| Evidence | Source | Workload | Finding |
|---|
Insufficient evidence
Collect relevant observations from different telemetry sources and compare workload identities and timestamps.
Incident Timeline
Root Cause Analysis
A missing alert is not proof of normal behaviour. Validate sensor coverage before concluding that a workload is safe.
Guided Kubernetes Security Investigations
0 / 6 completedEstablish Normal Behaviour
Correlate expected process execution with legitimate frontend-to-API and API-to-database communication.
Unexpected Container Shell
Correlate an unexpected shell execution with runtime detection evidence and contain the workload.
Suspicious External Egress
Correlate an unexpected worker process with an unapproved external network destination.
Unauthorized Lateral Communication
Investigate an unexpected development-to-production connection and verify network containment.
Sensitive File Access
Investigate unexpected access to a protected application file. Distinguish local execution containment from network isolation.
Missing Runtime Visibility
Identify a node-level telemetry coverage failure, restore monitoring and verify fresh observations.
Security Technology Comparison
| Technology | Primary role | Engineering consideration |
|---|---|---|
| Cilium | Networking and network policy enforcement | Identity, policy configuration and datapath coverage |
| Hubble | Network flow observability | Visibility depends on available observation points |
| Tetragon | Runtime observability and supported enforcement | Tracing policy, hooks and kernel compatibility |
| Falco | Rule-based runtime threat detection | Event source, rule coverage and alert quality |
| Kubernetes API | Workload metadata and control-plane operations | RBAC, audit configuration and identity correlation |
Production Investigation Principles
Correlate beyond IP addresses
Pod IP addresses can change. Use namespace, pod UID, container identity, process metadata and timestamps when correlating observations.
Distinguish detection from proof
A rule match is a detection signal. Correlate the observation with application context and other evidence before establishing an incident conclusion.
Verify the relevant security boundary
Network controls can restrict communication. Process-level threats may require separate runtime enforcement or workload lifecycle actions.
Runtime security is an evidence correlation problem.
Network telemetry, process observations, security alerts and Kubernetes workload metadata provide complementary perspectives. Effective investigation requires sufficient coverage, reliable identity correlation, contextual analysis and independent verification of containment.
Kubernetes Runtime Security and Policy Enforcement
Engineering continuous workload protection through kernel-level visibility, identity-aware networking, runtime security policies and evidence-driven cloud-native incident response.
1. Why Kubernetes Requires Runtime Security
Kubernetes security cannot end when a container image is scanned or a workload is admitted into the cluster. A legitimate image may contain a vulnerable application, receive malicious input, execute an unexpected process or attempt to communicate with an unauthorised destination after deployment.
Admission controls evaluate resources before they enter the cluster. Runtime security evaluates behaviour after workloads begin executing. These are complementary security boundaries.
Supply Chain Security
Image scanning, signed artifacts, software provenance, dependency analysis and trusted registries.
Deployment Governance
Pod Security Standards, admission policies, resource validation and restrictions on privileged workloads.
Runtime Protection
Process execution, file access, network connections, privilege changes and supported enforcement actions.
A compliant deployment is not necessarily a secure running workload. Runtime behaviour must be evaluated independently of deployment-time configuration.
2. Kubernetes Runtime Security Architecture
Containers normally share the Linux kernel of their worker node. Namespaces and cgroups provide isolation and resource boundaries, while the kernel remains responsible for executing system calls, scheduling processes, processing packets and applying security checks.
This shared execution environment makes the kernel an important observation point for cloud-native security.
Cilium
Identity-aware networking, connectivity, network policy enforcement and network observability through Hubble.
Tetragon
Kernel-level process and runtime security observability, policy-based event selection and supported enforcement actions.
Falco
Rule-based runtime threat detection using system activity and supported event sources, with alerts for external response.
| Capability | Cilium | Tetragon | Falco |
|---|---|---|---|
| Primary role | Networking and network security | Runtime observability and enforcement | Runtime threat detection |
| Network policy | Native capability | Runtime network-related instrumentation | Detection through available events |
| Process execution | Not its primary role | Process lifecycle visibility | Rule-based detection |
| File activity | Not its primary role | Selected kernel hooks and policies | Supported system event rules |
| Enforcement | Network traffic decisions | Supported signal or denial mechanisms | External response integration |
| Security output | Flow and policy verdicts | Process and tracing events | Structured security alerts |
3. DaemonSets and Node-Level Instrumentation
Runtime security agents are commonly deployed using Kubernetes DaemonSets. A DaemonSet schedules an agent on each eligible node, allowing instrumentation to operate close to the workloads it monitors.
Agent Responsibilities
Load and attach instrumentation, configure maps, consume kernel events, enrich workload metadata, manage policies and export security telemetry.
Operational Dependencies
Supported kernels, required privileges, host access, container runtime metadata, Kubernetes RBAC and reliable event transport.
Restrict administrative access to their configuration, images, service accounts and policy resources. Compromise of a node-level security agent can undermine the monitoring boundary itself.
4. Container Identity and Security Context
A raw kernel event may identify a process ID, executable, cgroup, namespace or socket. Security engineers need to associate that event with the Kubernetes workload responsible for the activity.
{
"event_type": "process_exec",
"cluster": "production-eu",
"node": "worker-02",
"namespace": "payments",
"pod": "payment-api-7b9d8",
"pod_uid": "example-pod-uid",
"container": "api",
"service_account": "payment-api",
"process": {
"pid": 18432,
"binary": "/bin/sh",
"parent_binary": "/app/payment-api"
},
"policy": "unexpected-shell-execution",
"action": "observe",
"severity": "high"
}
This is a conceptual normalised event, rather than the native output format of a particular security product.
Pod IP addresses and process IDs can be reused. Reliable investigations should retain cluster identity, node identity, Pod UID, container ID, timestamps and process lifecycle context.
5. Cilium Identity-Aware Network Enforcement
Traditional network policies often depend heavily on IP addresses. Kubernetes workloads are dynamic, and their addresses may change when Pods are rescheduled or replaced.
Cilium associates endpoints with security identities derived from relevant labels. Network policy can therefore describe permitted relationships between workloads rather than individual ephemeral addresses.
Example: Restricting Database Ingress
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: database-ingress
namespace: payments
spec:
endpointSelector:
matchLabels:
app: database
ingress:
- fromEndpoints:
- matchLabels:
app: payment-api
toPorts:
- ports:
- port: "5432"
protocol: TCP
This namespaced policy selects database endpoints and permits TCP port 5432 from matching payment API endpoints in the same namespace. Effective access also depends on other applicable policies and the cluster's policy enforcement configuration.
A compromised process inside an authorised payment API Pod may inherit the workload's permitted network relationships. Runtime process monitoring provides a separate layer of evidence.
6. Tetragon TracingPolicy Architecture
Tetragon provides kernel-level runtime security observability through eBPF. Its TracingPolicy resources allow engineers to describe instrumentation points, event selection criteria and supported actions.
Instrumentation Hooks
Identify supported kernel functions, tracepoints or other instrumentation points associated with the activity under investigation.
Argument Extraction
Capture relevant function arguments, return values or contextual information according to the selected hook.
Event Selectors
Reduce irrelevant activity by selecting supported process, binary, argument and workload-related attributes.
Policy Actions
Emit events or perform supported enforcement actions when configured conditions match.
Observation-First TracingPolicy Example
apiVersion: cilium.io/v1alpha1
kind: TracingPolicy
metadata:
name: observe-selected-file-open
spec:
tracepoints:
- subsystem: syscalls
event: sys_enter_openat
args:
- index: 1
type: string
selectors:
- matchArgs:
- index: 0
operator: Equal
values:
- "/etc/shadow"
This illustrative policy selects a specific filename argument at the openat syscall-entry tracepoint. It observes an attempted operation, not proof of successful access. It is not a complete file protection policy: alternative paths, other system calls and kernel compatibility must be considered.
Hook availability, argument types, selector support and enforcement capabilities depend on the Tetragon release, kernel version and configuration. Test the resource in an isolated cluster before production deployment.
7. Runtime Detection Versus Runtime Enforcement
Detecting a suspicious operation and preventing it are different engineering problems. An event generated after an operation completes cannot retroactively prevent that operation.
Observe
Record matching activity without changing workload execution. Useful for baselining and policy development.
Terminate
Deliver a supported signal to a selected process. Termination does not guarantee that earlier side effects are prevented.
Deny
Reject an operation at an appropriate supported enforcement point before the protected operation succeeds.
| Mechanism | Security outcome | Important limitation |
|---|---|---|
| Tracepoint observation | Capture execution evidence | Does not inherently prevent execution |
| Process signal | Request process termination | Operation may already have produced side effects |
| Supported return override | Reject eligible operations | Restricted by hook and kernel support |
| BPF LSM enforcement | Return a security denial at a supported hook | Requires appropriate kernel and policy support |
| Cilium network policy | Allow or deny selected traffic | Does not independently control every process action |
| External response | Quarantine or remediate a workload | Asynchronous response and orchestration latency |
Determine whether the selected mechanism runs before or after the protected operation, what action it can perform and whether failure leaves the workload in an acceptable security state.
8. Falco Runtime Threat Detection
Falco evaluates runtime events against security rules. Its detection engine can identify unexpected process execution, suspicious file activity, privilege-related behaviour and other events associated with potential workload compromise.
Example: Unexpected Shell Execution
- rule: Unexpected Shell in Payment API
desc: Detect shell execution in the payment API container
condition: >
evt.type in (execve, execveat) and
evt.dir = < and
evt.rawres = 0 and
container.id != host and
k8s.ns.name = payments and
container.name = api and
proc.name in (sh, bash, dash, ash)
output: >
Unexpected shell execution
(user=%user.name
process=%proc.name
parent=%proc.pname
container=%container.id
namespace=%k8s.ns.name
pod=%k8s.pod.name)
priority: WARNING
source: syscall
tags: [container, runtime, process]
This example looks for successful execution of selected shell processes inside a matching container. Kubernetes metadata must be available to the detection engine for those fields to match correctly.
Legitimate debugging, maintenance scripts and application startup behaviour can also produce shell execution events. Production rules should be tuned against expected workload behaviour.
9. Correlating Network and Runtime Security Evidence
A network flow alone may not explain why a connection was attempted. A process event alone may not establish whether the associated network traffic was permitted.
Combining runtime process evidence with Cilium and Hubble network telemetry can provide a more complete investigation.
Correlation Keys
Cluster, node, Pod UID, container ID, workload labels, process execution identity, network tuple and event timestamps.
Correlation Challenges
Clock skew, event loss, reused identifiers, NAT, asynchronous metadata updates and short-lived workloads.
10. Production Security Event Pipelines
Large Kubernetes clusters can generate substantial runtime telemetry. Exporting every available kernel event without filtering or capacity planning can overwhelm collection infrastructure and reduce the reliability of security monitoring.
Kernel Event Selection
Capture relevant activity using appropriate hooks, selectors and filtering mechanisms.
Node-Level Collection
Consume kernel events through supported buffers, enrich metadata and track collection health.
Event Transport
Deliver structured events through authenticated, encrypted and capacity-managed transport mechanisms.
Normalisation and Correlation
Map product-specific event formats into a consistent security schema while retaining original evidence.
Detection and Prioritisation
Combine policy matches, workload sensitivity, behavioural context and related security events.
Investigation and Response
Provide evidence to security operations, preserve incident records and coordinate authorised remediation.
Selected security events across a hypothetical cluster.
Approximately 12 MB/s before compression and transport overhead.
Approximate decimal storage volume before retention controls.
Monitor kernel buffer loss, agent CPU and memory consumption, exporter queues, transport errors, metadata enrichment failures and end-to-end event delivery latency.
11. Cloud-Native Incident Response
Consider a production payment API workload that unexpectedly launches a shell process and subsequently exhibits an outbound connection attempt. The following synthetic incident illustrates how multiple security layers contribute different evidence.
Shell execution observed within the payment API container.
Outbound traffic rejected by the applicable network policy.
Network denial does not establish that the workload is uncompromised.
Normal Payment API Execution
Application processes and permitted database connectivity are consistent with the expected workload profile.
Unexpected Child Process
Tetragon records shell execution associated with the payment API container and its process ancestry.
Falco Rule Match
The configured unexpected-shell detection rule generates a security alert.
Outbound Connection Denied
Cilium rejects traffic that is not permitted by the effective egress policy. Hubble records the corresponding verdict.
Incident Created
The security pipeline associates the runtime and network events with the same workload and investigation window.
Authorised Workload Isolation
Responders preserve relevant evidence and apply an approved containment procedure appropriate to the service.
Controlled Service Restoration
The suspected entry point is investigated, affected credentials are evaluated, and trusted workload replacements are deployed under the incident response procedure.
Blocking network traffic limits one potential consequence. It does not establish that malicious code, altered files, exposed credentials or other persistence mechanisms are absent.
12. Kubernetes Security Engineering CLI
Engineers should verify agent coverage, policy installation, workload identity and actual security events before drawing conclusions about enforcement effectiveness.
# Inspect worker nodes and workload placement kubectl get nodes -o wide kubectl get pods -A -o wide # Inspect node-level agent deployment kubectl get daemonsets -A # Inspect Kubernetes network policies kubectl get networkpolicies -A # Discover installed security APIs kubectl api-resources | grep -Ei 'cilium|tracingpolic' # Inspect workload labels and metadata kubectl get pods -n payments --show-labels kubectl describe pod -n payments <pod-name> # Inspect security agent logs kubectl logs -n <agent-namespace> <agent-pod> # Inspect Cilium policies, if installed kubectl get ciliumnetworkpolicies -A kubectl get ciliumclusterwidenetworkpolicies # Inspect Tetragon policies, if installed kubectl get tracingpolicies kubectl get tracingpoliciesnamespaced -A
# Requires configured Cilium CLI access cilium status # Requires configured Hubble connectivity hubble status # Inspect namespace-related flows hubble observe --namespace payments # Inspect dropped flows hubble observe --namespace payments --verdict DROPPED
# Run on an authorised Linux worker node uname -r sudo bpftool feature probe sudo bpftool prog show sudo bpftool map show sudo bpftool link show # Inspect kernel resource pressure cat /proc/pressure/cpu cat /proc/pressure/memory # Inspect node resource consumption vmstat 1
Commands require appropriate tools, permissions and installed components. Resource names, namespaces and available APIs vary between deployment configurations.
13. Production Runtime Security Failure Modes
| Failure condition | Security impact | Engineering investigation |
|---|---|---|
| DaemonSet coverage gap | Workloads execute without expected monitoring | Inspect scheduling, taints, selectors and agent readiness |
| Unsupported kernel hook | Policy cannot attach or operate as intended | Check kernel features, agent logs and policy status |
| Missing workload metadata | Events cannot be reliably associated with workloads | Inspect runtime metadata and Kubernetes API access |
| Kernel event loss | Incomplete incident evidence | Inspect buffer pressure, drop counters and CPU load |
| Overly broad detection rules | Alert fatigue and investigation overload | Baseline expected behaviour and refine selectors |
| Incorrect enforcement policy | Legitimate application operations disrupted | Review policy scope, staged rollout and rollback controls |
| Network policy conflict | Unexpected access or connectivity failure | Inspect all applicable policies and observed verdicts |
| Exporter congestion | Delayed or lost security alerts | Inspect queues, retries, transport and collector capacity |
| Agent upgrade regression | Reduced instrumentation or enforcement coverage | Validate compatibility and perform canary verification |
14. Engineering a Safe Runtime Policy Lifecycle
Discover
Understand normal process, file and network behaviour for each workload class.
Observe
Deploy detection-oriented policies and measure their coverage and operational overhead.
Validate
Test expected operations, prohibited behaviour, metadata accuracy and policy compatibility.
Canary
Introduce enforcement to a limited, controlled workload population with rollback available.
Enforce
Expand approved policies after verifying application reliability and the intended security outcomes.
Continuously Verify
Reassess policies after kernel upgrades, application changes, agent updates and infrastructure migrations.
From Kubernetes Connectivity to Continuous Runtime Protection
Effective Kubernetes security combines multiple independent controls. Cilium provides identity-aware network enforcement. Tetragon contributes kernel-level runtime observability and supported enforcement mechanisms. Falco evaluates runtime activity against security detection rules.
Kubernetes metadata transforms low-level execution events into workload-aware security evidence, while central event pipelines allow engineers to correlate process activity, network decisions and policy matches.
The engineering objective is not simply to generate more alerts. It is to establish reliable security boundaries, verify that those boundaries operate correctly and preserve sufficient evidence to investigate failures.
Runtime Policy Enforcement Simulator
Design, inspect and validate programmable runtime security policies. Follow workload operations through Linux kernel security hooks, evaluate workload identity and policy selectors, compare observation with enforcement and investigate the resulting security verdicts.
Linux Kernel Enforcement Architecture
ENFORCEMENT ENGINE READYProgrammable Runtime Security
Select any component to investigate its role in runtime policy evaluation and security enforcement.
BPF LSM
Attach supported eBPF programs to Linux Security Module hooks to evaluate selected security-sensitive operations. Appropriate hooks can return an error to prevent an operation.
Tetragon
Observe selected process and kernel events using tracing policies. Tetragon also supports specific enforcement mechanisms, subject to hook and kernel capabilities. This laboratory models its observation role.
cgroup Network Hooks
Evaluate selected socket connection operations at cgroup attachment points. This is distinct from packet-level enforcement using XDP or TC.
Runtime Security Policy Builder
In this teaching model, an applicable deny takes precedence over an allow marker. An audit action generates evidence without preventing the operation. An allow marker cannot override another applicable denial.
Installed Policy Registry
0 installed policiesIllustrative policy model only. The representation below is not deployable Tetragon, Kubernetes or BPF LSM syntax.
Policy Decision Evidence
| Policy | Identity | Operation | Mechanism | Decision |
|---|
No operation evaluated
Generate an operation to inspect selector matching, unavailable mechanisms and final enforcement resolution.
Kernel Security Event Console
SYNTHETIC KERNEL EVENTSSecurity Telemetry Buffer
0 / 8 recordsTelemetry loss does not necessarily disable enforcement.
This model separates policy execution from event export. A full telemetry buffer can lose audit records while applicable kernel enforcement continues to operate.
Exported Security Evidence
| Event | Workload | Operation | Verdict |
|---|
Runtime Enforcement Operation History
SIMULATOR GROUND TRUTH| Operation | Workload | Requested action | Matched policies | Verdict | Telemetry |
|---|
Ground truth is provided by the simulator for education. In a production incident, engineers must establish operation outcomes through available evidence rather than assume access to a complete event history.
Guided Runtime Security Investigations
0 / 6 completedObserve Without Blocking
Install an audit policy for unexpected frontend shell execution. Generate the operation and confirm that it is observed but permitted.
Prevent Unexpected Execution
Install a BPF LSM denial for frontend shell execution. Verify that the shell is denied while approved application execution remains permitted.
Protect Sensitive Files
Restrict protected file access by the development workload without blocking the authorized API service.
Enforce Network Boundaries
Deny unapproved external connections from the frontend while preserving approved internal service communication.
Investigate Missing Enforcement
A policy is configured but its security mechanism is unavailable. Observe the resulting protection gap, restore the mechanism and repeat the operation.
Enforcement Under Telemetry Pressure
Disable the telemetry collector, generate a burst of denied operations and demonstrate that audit loss does not change the modeled enforcement verdict.
Security Mechanism Comparison
| Mechanism | Security role | Enforcement boundary |
|---|---|---|
| BPF LSM | Security policy evaluation | Supported LSM hooks |
| Tetragon | Runtime observation and supported enforcement | Configured tracing policies and supported actions |
| Falco | Rule-based runtime detection | Alert generation; external response integrations |
| cgroup BPF | Workload-associated network controls | Supported socket and network attachment points |
| XDP / TC | Programmable packet processing | Packet-level network processing |
| Seccomp | System call filtering | Process system call interface |
Production Enforcement Principles
Validate before enforcing
Establish expected workload behaviour, observe potential matches and test enforcement against representative legitimate application operations.
Configuration is not proof of protection
Verify that required kernel features, program loading, attachment points and policy selectors are operational.
Choose the correct security boundary
File access, process execution, socket operations and packet forwarding represent different enforcement boundaries. A single policy mechanism cannot replace every other security control.
Effective runtime security requires verified enforcement, precise policy scope and reliable evidence.
An installed policy does not guarantee an active security boundary. Engineers must verify attachment availability, selector accuracy, application compatibility, enforcement outcomes and the integrity of the telemetry pipeline.
Production eBPF Architecture, Performance Engineering and Troubleshooting
Engineering reliable kernel-level observability and runtime security platforms across enterprise Linux infrastructure, Kubernetes clusters and distributed cloud environments.
1. Designing eBPF for Production Infrastructure
Running an eBPF program successfully on a development machine is fundamentally different from operating thousands of instrumented workloads across heterogeneous production infrastructure.
Production environments introduce different kernel versions, CPU architectures, workload profiles, security requirements, event rates and operational failure conditions.
The engineering challenge is to maintain useful visibility and reliable enforcement without introducing unacceptable resource consumption or infrastructure instability.
Instrumentation Plane
Kernel hooks, verified BPF programs, maps, event buffers and supported enforcement mechanisms.
Management Plane
Program deployment, configuration, policy distribution, compatibility management and controlled upgrades.
Telemetry Plane
Event consumption, enrichment, buffering, transport, storage, analysis and security investigation.
Treat instrumentation as part of the infrastructure. It requires capacity planning, lifecycle management, monitoring, security governance and failure recovery.
2. Kernel Compatibility and Feature Discovery
Linux kernel version numbers alone do not establish eBPF compatibility. Distribution backports, kernel configuration, security restrictions and architecture-specific support influence the capabilities available to an eBPF application.
| Compatibility dimension | Engineering significance | Validation |
|---|---|---|
| BPF program types | Determine which execution environments are supported. | Feature probing and test loading. |
| BTF availability | Supports type-aware instrumentation and common CO-RE workflows. | Inspect kernel BTF and relocation results. |
| Helpers and kfuncs | Determine available operations within a program context. | Validate against the target program type and kernel. |
| Attachment mechanisms | Determine whether required hooks can be instrumented. | Inspect actual attachment results. |
| JIT support | Influences execution performance and supported configurations. | Inspect kernel configuration and loaded program information. |
| Security configuration | Capabilities, lockdown and LSM restrictions may affect loading. | Inspect permissions and kernel diagnostics. |
# Identify kernel and architecture uname -r uname -m # Probe supported BPF features sudo bpftool feature probe # Inspect kernel BTF availability ls -lh /sys/kernel/btf/vmlinux # Inspect available tracepoints sudo bpftrace -l 'tracepoint:*' # Inspect supported BPF filesystem mounts findmnt -t bpf # Inspect relevant kernel configuration when available grep -E 'CONFIG_BPF|CONFIG_DEBUG_INFO_BTF' \ /boot/config-$(uname -r)
Compile Once – Run Everywhere helps adapt programs to target kernel type layouts. It does not create missing hooks, helpers, program types or enforcement capabilities.
3. Understanding Instrumentation Overhead
eBPF executes code in response to selected events. The total resource cost depends on how frequently those events occur, how much work each program performs and how much telemetry is exported into userspace.
Execution Frequency
A program attached to a high-frequency networking or scheduling event may execute millions of times per second.
Program Complexity
Map operations, stack collection, argument extraction, filtering and helper calls contribute to execution cost.
Event Export
Buffer reservation, event copying, userspace consumption, enrichment and transport create additional resource demand.
Estimated BPF Execution CPU Demand
For example, 500,000 invocations per second at an average execution cost of 400 nanoseconds consume approximately 0.2 CPU cores of aggregate BPF execution time.
This excludes userspace processing, telemetry transport, cache effects and other indirect costs.
4. Measuring BPF Program Performance
Production performance engineering requires a baseline. Engineers should compare workload behaviour before and after instrumentation is introduced under representative load.
Application response latency.
Response latency with instrumentation.
Relative increase in p95 latency.
Example node CPU utilisation increase.
These synthetic measurements illustrate how instrumentation should be evaluated against application performance objectives. A small absolute latency increase may still be unacceptable for latency-sensitive infrastructure.
sudo bpftool prog show sudo bpftool -j prog show # Inspect a selected program sudo bpftool prog show id 42 # Inspect translated instructions sudo bpftool prog dump xlated id 42 # Inspect JIT-generated instructions where supported sudo bpftool prog dump jited id 42
Where BPF runtime statistics are enabled, program information may include cumulative run counts and execution time. These counters can support interval-based measurements.
Program ID: 42 Measurement interval: 10 seconds Run count at start: 12,000,000 Run count at end: 17,000,000 Runtime at start: 4,800,000,000 ns Runtime at end: 6,800,000,000 ns Invocation delta: 5,000,000 Runtime delta: 2,000,000,000 ns Average execution time: 400 ns Invocation rate: 500,000/sec Aggregate CPU demand: 0.2 cores
BPF runtime statistics, profiling and detailed tracing should be enabled deliberately. Verify their operational impact and avoid unnecessary continuous profiling.
5. BPF Map Capacity and Memory Engineering
BPF maps provide shared state between kernel programs and userspace applications. They can hold connection state, counters, policy information, process metadata and other information required by instrumentation.
100,000 Entries
100,000 × (16-byte key + 64-byte value).
Raw key/value payload only. Allocation metadata, alignment, hash structures and implementation overhead increase actual memory requirements.
100,000 Entries × 32 Possible CPUs
100,000 × 64-byte value × 32 possible CPUs.
Value storage alone, excluding keys, alignment and map implementation overhead.
Per-CPU maps can reduce contention for frequently updated state, but they may significantly increase memory consumption. Their allocation can depend on the number of possible CPUs, not merely the number currently online.
| Map type | Typical purpose | Production consideration |
|---|---|---|
| Hash | Dynamic key/value state | Capacity exhaustion and lookup/update costs. |
| Array | Fixed-index configuration or counters | Preallocated storage and fixed capacity. |
| Per-CPU hash or array | High-frequency CPU-local state | Memory multiplication and aggregation costs. |
| LRU hash | Bounded dynamic state | Eviction can remove entries still useful to the application. |
| LPM trie | Longest-prefix matching | Prefix population and lookup workload. |
| Ring buffer | Kernel-to-userspace event transport | Finite capacity and reservation failures under pressure. |
sudo bpftool map show sudo bpftool -j map show # Inspect a selected map sudo bpftool map show id 17 # Inspect pinned objects sudo find /sys/fs/bpf -maxdepth 3 -type f # Dump selected map contents only when authorised sudo bpftool map dump id 17
Map metadata exposes configured capacity, but occupancy measurement depends on the map type and application. Prefer application-provided counters over repeatedly dumping large production maps.
6. Event Buffers, Backpressure and Telemetry Loss
Kernel instrumentation may generate events faster than userspace agents can consume them. This creates pressure on finite event buffers and downstream collection infrastructure.
Selected kernel events.
Maximum sustained consumption in this example.
Steady-state deficit relative to generated events.
Increasing buffer capacity can absorb temporary bursts. It cannot resolve a sustained mismatch between production and consumption rates.
Use appropriate kernel-side filtering, aggregation and workload selection. Preserve the security-critical events required for investigations rather than applying indiscriminate sampling to every event category.
7. Verifier Failures and Program Loading Diagnostics
The Linux BPF verifier evaluates programs before allowing them to execute. Rejection may result from unsafe memory access, invalid pointer operations, unsupported helper usage, excessive analysis complexity or other violations.
| Diagnostic category | Potential cause | Engineering response |
|---|---|---|
| Invalid memory access | Insufficient bounds or null-pointer validation. | Establish valid access on all relevant execution paths. |
| Uninitialised stack | Reading stack memory before writing valid data. | Initialise required fields before use. |
| Unsupported helper | Helper unavailable for the kernel or program type. | Check feature support and choose a valid alternative. |
| Complexity rejection | Excessive verifier state exploration. | Simplify control flow and reduce unnecessary branching. |
| Relocation failure | Required target types or fields unavailable. | Inspect BTF and CO-RE relocation diagnostics. |
| Permission failure | Insufficient capabilities or security restrictions. | Review authorised deployment privileges and security policy. |
# Inspect ELF sections llvm-readelf -S program.bpf.o # Inspect BPF instructions and source mapping llvm-objdump -S program.bpf.o # Inspect object BTF where available bpftool btf dump file program.bpf.o format raw # Review kernel diagnostics sudo journalctl -k --since "15 minutes ago" # Review security agent diagnostics kubectl logs -n <namespace> <agent-pod>
Detailed verifier logs are normally requested by the userspace loader during program loading. Kernel logs alone may not contain the required verifier output.
A verified program may still implement incorrect policy, generate excessive telemetry or produce misleading observability data. Functional and performance validation remain necessary.
8. Loaded Programs, Attachments and Object Lifetime
A BPF program being present in the kernel does not establish that it is attached to the intended execution point. Loading, attachment and runtime invocation are distinct stages of the instrumentation lifecycle.
Loaded
The program has been accepted and a kernel BPF object exists. It may not yet be attached to any hook.
Attached
An appropriate attachment mechanism connects the program to an execution point.
Executing
Relevant runtime activity invokes the program, potentially updating state or generating events.
# Loaded programs sudo bpftool prog show # BPF link objects sudo bpftool link show # Network-related BPF attachments sudo bpftool net show # Cgroup-related attachments sudo bpftool cgroup tree /sys/fs/cgroup # Inspect traffic-control attachments sudo tc filter show dev eth0 ingress sudo tc filter show dev eth0 egress # Inspect interface configuration ip -details link show dev eth0
Not every attachment mechanism is represented by a BPF link object. Use inspection tools appropriate to the specific networking, tracing or security attachment.
Object lifetime depends on kernel references, file descriptors, attachment mechanisms and pinned objects. Some instrumentation may persist after the original userspace process exits.
9. Security Agent Reliability and Failure Behaviour
Production runtime security requires a clear understanding of what happens when an agent crashes, a node restarts, a policy update fails or central telemetry becomes unavailable.
| Failure | Possible impact | Required validation |
|---|---|---|
| Userspace agent crash | Event consumption and policy updates may stop. | Determine which kernel objects and attachments persist. |
| Node reboot | Kernel-resident BPF objects are lost. | Verify automatic instrumentation restoration. |
| Collector unavailable | Delayed or lost exported telemetry. | Verify queue limits, retry and failover behaviour. |
| Policy deployment failure | Expected enforcement may not become active. | Check effective policy status and runtime tests. |
| Map capacity exhausted | State updates may fail or entries may be evicted. | Validate application-specific capacity handling. |
| Kernel upgrade | Compatibility or attachment regressions. | Run feature checks and controlled canary validation. |
Fail-Open Behaviour
Workload operations remain available when a security control cannot enforce its intended policy.
Availability may be preserved at the cost of reduced protection.
Fail-Closed Behaviour
Protected operations are rejected when the required security condition cannot be established.
Protection may be preserved at the cost of workload availability.
These behaviours are implementation-specific. Engineers must test actual failure conditions rather than assume that every eBPF-based product offers a configurable fail-open or fail-closed mode.
10. High-Availability Telemetry Infrastructure
Bounded Queues
Absorb temporary transport interruptions without allowing uncontrolled memory consumption.
Durable Delivery
Use appropriate persistence and acknowledgement mechanisms when security evidence must survive restarts.
Event Deduplication
Retries can generate duplicate events. Retain stable event identifiers where supported.
Transport Security
Authenticate agents and protect telemetry against unauthorised access or modification.
Time Synchronisation
Maintain consistent timestamps and account for clock skew during distributed investigations.
Retention Governance
Protect sensitive process arguments, workload metadata and other potentially confidential evidence.
11. Production Observability and Security SLOs
The instrumentation platform itself must be observable. A healthy application does not necessarily imply that security telemetry is being collected successfully.
Illustrative target for eligible nodes.
Example activation reliability objective.
Example maximum loss objective for a defined event class.
Example p99 event delivery objective.
These are illustrative engineering objectives, not universal product guarantees. Security-critical event classes may require stricter controls and explicit handling of any loss.
| Metric | What it reveals | Investigation trigger |
|---|---|---|
| Agent coverage | Expected nodes with operational instrumentation. | Missing or unhealthy node agents. |
| Policy activation status | Whether required instrumentation is installed. | Rejected, pending or inactive policies. |
| Program invocation rate | How frequently instrumentation executes. | Unexpected increase or disappearance of activity. |
| Map update failures | Potential capacity or state management problems. | Sustained failures or unexpected eviction. |
| Buffer reservation failures | Kernel-side telemetry loss or pressure. | Increasing loss counters. |
| Exporter queue depth | Downstream transport pressure. | Persistent queue growth. |
| Event delivery latency | Delay between event generation and ingestion. | Violation of the defined delivery objective. |
| Workload performance | Potential instrumentation impact. | Latency, throughput or resource regressions. |
A silent security platform may indicate normal behaviour, incorrect event selection, missing instrumentation or telemetry failure. Continuously verify the monitoring path.
12. Production Troubleshooting Case Study
Consider an enterprise Kubernetes cluster experiencing increased application latency and reduced security visibility after an instrumentation policy update.
The following synthetic incident demonstrates how engineers can distinguish application problems from instrumentation overhead and telemetry bottlenecks.
Baseline: 24 ms
Baseline: 48%
Baseline: 0.02%
No central saturation observed.
Normal Infrastructure Behaviour
Application latency and telemetry delivery remain within the expected operating range.
New Runtime Observation Policy
A policy introduces detailed argument collection on a high-frequency kernel execution path.
Application Latency Increases
Node CPU consumption rises and application response times begin violating their normal baseline.
Kernel Event Loss Detected
Event generation reaches 120,000 events per second while node-level consumption remains at 90,000 per second.
Central Collector Saturation Ruled Out
Collector capacity and network transport appear healthy. Evidence points towards node-local processing.
Instrumentation Cost Identified
Program runtime statistics and controlled comparison identify the newly introduced high-frequency tracing policy as the primary contributor.
Rollback of Regressing Observation Policy
The previous validated observation configuration is restored while required security enforcement remains active.
Performance and Telemetry Recover
Application latency approaches baseline and event loss returns to its previous operating range. Engineers retain incident evidence and prepare a narrower replacement policy.
Excessive Instrumentation
Broad event selection, expensive argument extraction, increased kernel execution cost and saturated local consumption.
Controlled Instrumentation
Validated observation scope, reduced event volume, restored application performance and reliable telemetry delivery.
Temporal correlation with a policy update is a useful starting point. Program statistics, workload comparison and recovery after a controlled rollback provide stronger evidence of causation.
13. The Production eBPF Troubleshooting Methodology
Establish the Symptom
Determine whether the problem concerns application performance, missing telemetry, policy enforcement, program loading or infrastructure reliability.
Identify the Scope
Determine affected nodes, workloads, kernel versions, agent versions and policy populations.
Verify Compatibility and Deployment
Inspect kernel capabilities, agent health, loaded programs, map creation and actual attachments.
Inspect Runtime Execution
Evaluate invocation frequency, execution time, state update failures and relevant workload behaviour.
Trace the Telemetry Path
Investigate kernel buffers, userspace consumption, enrichment, exporter queues, transport and central ingestion.
Correlate Infrastructure Changes
Review kernel upgrades, application releases, policy changes, traffic growth and agent deployments.
Apply Controlled Mitigation
Use approved rollback, policy refinement or capacity adjustments while preserving required security boundaries.
Validate Recovery
Confirm application performance, telemetry completeness, policy activation and expected security behaviour.
14. Enterprise Deployment and Upgrade Strategy
Versioned Policies
Maintain reviewed policy definitions, configuration history and reproducible deployment artifacts.
Compatibility Matrix
Track validated kernel, distribution, CPU architecture and security agent combinations.
Performance Gates
Require acceptable workload latency, CPU consumption and event delivery before expanding a rollout.
Enforcement Tests
Verify permitted and prohibited behaviour using controlled test workloads.
Lifecycle Management
Manage program replacement, pinned objects, map compatibility and attachment cleanup.
Rollback Readiness
Maintain a tested recovery procedure that accounts for both application availability and security coverage.
15. Production Engineering Readiness Checklist
| Engineering domain | Required production evidence |
|---|---|
| Kernel compatibility | Required features verified on every supported node class. |
| Program lifecycle | Loading, attachment, replacement and cleanup tested. |
| Security enforcement | Expected allow and deny outcomes validated. |
| Performance | Representative workload benchmarks and overhead budgets. |
| Map capacity | Memory requirements and capacity failure behaviour understood. |
| Telemetry integrity | Event loss, queue pressure and delivery latency monitored. |
| Agent availability | Node coverage, restart behaviour and recovery tested. |
| Central collection | Collector failure and transport interruption exercises completed. |
| Governance | Authorised policy changes, access control and audit history. |
| Incident response | Investigation procedures and evidence retention established. |
| Upgrade management | Canary rollout and validated rollback procedures available. |
Engineering the Programmable Linux Kernel
eBPF introduces a powerful architectural capability: programmable execution within selected Linux kernel environments without requiring every instrumentation capability to be implemented as a traditional kernel module.
Across this engineering guide, we have examined the relationship between userspace and kernel execution, BPF program verification, maps, JIT compilation, programmable networking, runtime threat detection, observability and Kubernetes security.
The value of eBPF is not simply its ability to execute programs inside the kernel. Its value comes from placing carefully selected instrumentation and policy decisions close to the events that matter.
Successful production engineering requires understanding those execution boundaries, selecting appropriate hooks, controlling resource consumption and verifying that the resulting security and observability systems remain reliable.
eBPF Engineering Command Centre
Operate a simulated production Kubernetes infrastructure. Investigate eBPF deployment failures, inspect kernel capabilities, troubleshoot program attachment, manage resource consumption, restore telemetry pipelines and validate runtime security coverage through evidence-based engineering investigations.
Production Infrastructure Digital Twin
SIMULATION READYWorker Node 01
Select a worker node to inspect its deployment state, program inventory and resource consumption.
Infrastructure Alert Centre
0 active alertsKernel Compatibility and Deployment Inventory
| Capability | Current state |
|---|
Kernel version alone does not establish eBPF feature availability. Kernel configuration, BTF, attachment support, privileges and distribution-specific backports also influence deployment compatibility.
Cluster Program Attachment Registry
DESIRED STATE VS ACTUAL STATE| Node | Program | Attachment | Load state | Attachment state | Purpose |
|---|
Production Fault Injection Chamber
Introduce a controlled infrastructure failure on the selected node and investigate the resulting symptoms.
Fault injection modifies only this browser-based simulation. It does not access the host operating system, Kubernetes cluster or real eBPF programs.
Engineering Remediation Console
Correcting a compatibility or verifier problem does not automatically prove that programs have been reloaded and attached. Verify the actual deployment state.
Selected Node Performance History
CPU is expressed as a percentage of one CPU core. The chart clips values above 100%; the numerical dashboard retains the full modeled value.
Telemetry Pipeline and Resource Accounting
Previously queued events plus newly generated events equal exported events, lost events and remaining queued events for each modeled interval.
Estimated map memory and ring buffer capacity are reported separately. Actual BPF memory consumption depends on map type, allocation strategy, metadata, CPU count and kernel implementation.
Engineering Diagnostic Terminal
Output is synthetic and deliberately abbreviated. Actual command availability, privileges, agent names and output formats depend on the deployed environment.
Engineering Incident Timeline
| Time | Node | Engineering event |
|---|
Symptom → Evidence → Root cause → Remediation → Validation
Use the timeline to distinguish the original failure from subsequent operational changes. Validate that the intervention actually restored the required state.
Baseline vs Current Infrastructure State
Worker 01| Engineering property | Reference baseline | Current state | Assessment |
|---|
Resource comparisons use the same current workload rate and observability sampling setting. This helps separate configuration-induced overhead from changes in application workload intensity.
Guided Production Engineering Investigations
0 / 6 completedKernel Compatibility Failure
A worker cannot load the required CO-RE programs. Investigate BTF availability, restore compatibility and verify successful program attachment.
Program Verifier Rejection
A runtime security program fails verification. Inspect loader evidence, deploy a corrected program and restore the missing security attachment.
Excessive Kernel Overhead
An expensive tracing program consumes excessive CPU. Compare resource measurements and optimize execution without disabling required security checks.
BPF Map Memory Pressure
Oversized map allocation exceeds the engineering memory budget. Inspect map inventory and restore appropriate resource sizing.
Telemetry Pipeline Failure
A stalled collector causes queue growth and event loss. Restore collector throughput and demonstrate loss-free operation under a representative workload.
Silent Security Coverage Gap
The node agent is present but a required runtime security program is detached. Identify the missing hook and verify restored attachment coverage.
The Silent Kernel Incident
A production cluster has experienced multiple simultaneous eBPF failures following an infrastructure change. Security visibility is incomplete, telemetry is being lost and application nodes are experiencing resource pressure. Investigate the entire infrastructure and restore service without weakening required runtime security coverage.
Production Engineering Reference Budgets
| Indicator | Laboratory target |
|---|---|
| Required program attachment | 100% |
| Required security coverage | 100% |
| eBPF CPU overhead | ≤ 8% of one core per node |
| Estimated map allocation | ≤ 64 MiB per node |
| Ring buffer occupancy | Below 80% |
| Telemetry loss | Zero during validation |
| Recovery validation | 10 consecutive simulated seconds |
These are illustrative engineering budgets for this laboratory, not universal production recommendations.
Production Engineering Principles
Agent availability is not attachment health
A running userspace agent does not establish that every required kernel program has loaded and attached.
Measure before reducing visibility
Investigate execution frequency, program cost, map allocation and collector throughput before removing important instrumentation.
Missing telemetry is not proof of safety
Event loss, unavailable hooks and detached programs can create incomplete security evidence even when workloads appear operational.
- AI Agent Identity and Authorization Architecture Explained - November 25, 2026
- eBPF Runtime Security and Observability Explained - November 25, 2026
- NVIDIA BlueField DPU Architecture Explained - November 25, 2026
