Counting up to n packets and using that as trigger

I would like to implement a way for the P4 switch to count to n ingress packets, and at that time, to trigger a set of actions for sampling a packet (like gather information about it and send it to an external controller) but nevermind the latter part for now.
First to count to n packets, would this best be implemented using a counter or register? And then how do I read that value within the P4 program and put it in an if statement as a trigger?

Thank you

Hi @yiwen,

As you can find in the P4_16 spec, you can associate a direct/indirect counter to a table. So, you can count the packets that match a certain entry. Unfortunately, till now does not exist an extern/ “function” that allow you to read counter in the P4 program, you can read it via P4Runtime ( While, you can read an write a register in the P4 program and via P4Runtime, but I think that are not the right structure. You could try to use Meter (they should be similar to counters), the have 3 different leve of color “metadata” and you can use them as a trigger in your P4 code.

Thank you for the reply. I’m not sure about using meters, because for meters you set a rate, but in this case I’m trying to do an action every n packets, whatever the rate is. I thought about using counters in the beginning but as you say counters can only be read by an external controller via P4Runtime. And I’m not really sure about registers


Maybe my comment is useless, but you can define Meter in packest or bytes. So, you can counting the packets and apply an action/do a manipulation of the packets. You do not have a fine count, but perhaps it is the right trade-off compared to using registers, in terms of memory occupancy, latency, computation resources, etc.

There are no useless comments :slight_smile:

As DavideS mentioned, counters can be used to count events, but almost every P4 implementation I am aware of does NOT allow the data plane to read the values of counters. This is by design, because in a high speed implementation, there are tricks you can take advantage of in the hardware that make such unreadable-from-the-data-plane counters cheaper to implement than readable-from-the-data-plane counters, and such unreadable-from-the-data-plane counters are very very frequently used in production data planes.

I would recommend looking into P4 register arrays. They can be used to implement readable-from-the-data-plane counters, as well as fancier things than counters that can be read from the data plane.