DJL
DJL

Reputation: 166

Best practices for expressing metrics such as rates in JSON through an API where the result could be infinite or involve a division by 0?

I am working on an API (in Go) that queries and exposes sales data that will eventually be consumed by a charting/visualization library (not sure which one yet but will likely be React/JS based).

One of the metrics I have been asked to collect is a "Spend Lift", comparing how much more customers signed up for a rewards program spend over their non-enrolled peers.

This is computed as:

spend_lift = (avg_rewards_user_spend_per_order) / (avg_non_rewards_user_spend_per_order)

When dealing with normal transactional volume on the order of thousands of orders a day, there will most certainly be a healthy mix of reward and non-reward users, so this won't be common in practice, but how would/should one handle situations where all ordering customers over a given window of time (say hourly), or on a Q/A or developer box, are using rewards?

The spend lift in that case would approach infinity and be a divide by 0 case internally.

How should I approach sharing these values in my API? I can see a few solutions:

  1. Use null - the front-end application could interpret that as unrepresentable/out of bounds and discard it, which it may want to anyways for the sake of normalizing data - I am hesitant to use null because it can't differentiate positive and negative infinity if wanting to ceil or floor the data.
  2. Return the largest positive and negative values, respectively, for my data type (go float64), depending on the sign of the numerator - I like this approach because JSON numerics can't be infinite, and I presume the front-end framework would expect numbers.
  3. Return 0 - I have the same issue here as with null. It can't differentiate numerator signs, and 0 is also a valid value (e.g. if no customers are rewards enrolled).

I currently implemented a safe division helper in my backend that resorts to returning 0.

Upvotes: 0

Views: 27

Answers (0)

Related Questions