How to implement server-to-server frequency capping using cookies
Frequency capping lets you limit the number of times a specific user is shown a particular ad within a specified period. While you can easily enforce it using our zone tags, you can also implement frequency capping on a server-to-server basis using first-party cookies and our AdServe endpoint. This method stores the view count in the cookie, saving you from storing or mapping the data elsewhere.
When you request an ad via our API, you can include the array user_freq
. It contains the placement ID, the view count, and your desired start and expiry dates in integer format.
"user_freq": [
{
"placement_id": 11111111,
"start": 1604465307,
"expiry": 1606193307,
"views": 2
}
You must then define and update a cookie to store those data.
Read the frequency cookie.
Pass the
user_freq
data from the cookie into the ad request. Ensure that the values ofstart
andexpiry
are cycled for any placement that has passed the value ofexpiry
.
user_freq_json
instead of user_freq
. However, we recommend requesting via POST because the object can get large if the user has seen many ads.Extract the value of
placement_id
from the response, find the corresponding placement inuser_freq
, then increment the view count.Update
user_freq
and write it back to the cookie when serving the ad.
Depending on your security policies, you may want to encode the cookie data to prevent tampering.
Here's a sample implementation:
def handle_ad_request(request):
user_freq = read_frequency_cookie(request)
# Prepare ad request payload
ad_request_payload = {
"ID": 11111,
"setID": 123456,
"type": "json",
"size": "300x200",
"rf": 1,
"kw": ["string"],
"referrer": request.referrer,
"ip": request.remote_addr,
"ua": request.user_agent.string,
"sw": request.screen_width,
"sh": request.screen_height,
"spr": request.screen_pixel_ratio,
"pid": 123456,
"place": 1,
"user_freq": user_freq,
"_abdk_json": {
"bird": "duck",
"bug": "ant"
},
"defer_signing": False
}
# Make the ad request (this would typically be an HTTP request to the ad server)
ad_response = make_ad_request(ad_request_payload)
# Process ad response
placement_id = ad_response['placements'][0]['placement_1'][0]['placement_id']
user_freq = update_frequency_data(user_freq, placement_id)
# Prepare response and write updated frequency cookie
response = make_response(ad_response)
response = write_frequency_cookie(response, user_freq)
return response