Q:

Best way to model a quota system for a subscription messaging service

I have a rails application that has a subscription aspect with three plan levels depending on price tier. For example, 0-1000 messages is $10, 1001-10000 is $20, and a $0.01 surcharge on both for going over the quota amount.
Each User has many Messages. What's the best way (high level) to keep track of each user's message usage and overages and charge them accordingly?

A:

I think you'll need these elements:

Way to track number of messages (caching)
Way to track payment system (how to calculate surcharges etc)
Scheduled process of charging

Messages
To track the sent messages, you need a caching system (calculating on the fly will be expensive). I don't have that much experience here, but I'd recommend looking at Redis (you may wish to research caching here)
I would use Redis to store a key/value pair for all the month's messages. So when a message is created in your DB, have a mechanism to add the update to a Redis hash (which will belong to a user ID) 

Instagram info on Redis
Redis Hashes (store message date per username)

The Redis key/values will be to store the message timestamp (created_at) & the user_id of the message. This means you'll be able to reference the month's Redis store & dump to another db (to reference later on), allowing you to calculate how many messages each user sent

Payments
To enable a tier-based pricing structure, you'll need to be able to calculate the monthly invoices to send out. This should be an internal system, basically creating a mechanism to present a user with an invoice, and sending them to a payment provider to transfer the funds
To calculate the invoice, you'll basically need to run a rake task to do this:

Cycle through the user's Redis store
Store the Redis store in a db (maybe)
Take a "count" of messages
Use simple algorithm to determine price
Create priced invoice & associated record in invoice_messages table (where you can itemise message usage)

Scheduling
Although a relatively small feature, you'll need to schedule your invoice creation
I'm actually thinking about this currently (not much experience), so to do this, you'll need to set up a rake task to cycle through when a user should be invoiced. Depending on your app, you'll have to determine the right invoice date & then run the previous steps depending on it 

