You might want to consider asking a similar question on meta, to see if Jeff is willing to share any of his lessons learned in this arena. If you do, the question should be specifically about the way SO approached the problem. This question, however, is a perfectly valid question for this site (since it is asking about created a new project, inspired by what was done on SO).
I suspect, though, that the SO team has a job that periodically runs a set of queries to look for new badges to award, and then awards them. This is why badges aren't awarded immediately after the action is taken to earn them.