Since you're talking about Apache, I'll assume you're trying to protect brute-force HTTP Authentication style logins.
That's something I'm quite sure you will have a hard time doing within a traditional CGI environment.
Have you ever worked with
mod perl?
There are some good starter docs at
modperl.com, and one seems specifically tailored to your needs:
Blocking Greedy Clients.
I'm sure this could easily be modified to suit your purpose.
--twerq