GAMIFICATION GUIDES

How to Build an Energy Feature

Author
Jason LouroJason Louro

Your team wants to add an energy system. Users consume energy for actions. Energy regenerates over time. Cap it at a maximum. Seems like simple arithmetic. Three weeks later, you're debugging regeneration timing, handling edge cases around maximum caps, and dealing with race conditions when users perform rapid actions.

Energy systems appear straightforward until you implement them at scale. The core concept (limited resource that regenerates) hides complexity. When does regeneration happen? What if users act while at zero energy? How do you handle time zones for regeneration timing? What prevents users from gaming the system?

Trophy handles energy systems including regeneration, consumption, and metering. The complete implementation guide walks through the full process. Integration takes 1 day to 1 week. But understanding what building from scratch involves helps you make informed build versus buy decisions.

Key Points

  • Technical challenges in energy system implementation
  • Regeneration patterns and timing considerations
  • Consumption triggers and usage metering
  • Integration examples with Trophy's API
  • Build versus buy considerations for energy features

The Technical Reality

Before building energy systems, understand the problems beyond simple counters.

Time-based regeneration needs careful implementation. Energy regenerates hourly or daily, but when exactly? Server-scheduled jobs create spiky regeneration patterns. Per-user timers scale poorly. Event-driven regeneration requires complex triggering. Getting this right takes time.

Maximum cap handling prevents infinite accumulation. Users hit the cap and stop regenerating. But what if regeneration happens while they're at cap? Do they lose potential energy? How do you communicate this clearly? Edge cases around caps create complexity.

Consumption timing affects user experience. Immediate energy deduction prevents spam but blocks users at zero. Deferred consumption allows actions but creates debt states. Partial consumption for partial actions adds more complexity.

Race conditions happen when users perform rapid actions. Two actions at 5 energy each when user has 8 energy total. Which succeeds? Do they both check balance simultaneously and both succeed, overdrawing the account? Proper locking prevents this but adds latency.

Time zone handling for regeneration schedules requires per-user logic. Daily regeneration at midnight means different times for different users. Trophy handles time zones automatically, but building this yourself means complex timezone math.

Building production-ready energy systems typically takes 3-6 months including regeneration logic, consumption triggers, and edge cases. Trophy's infrastructure handles these problems, reducing implementation to integration work.

Architecture Patterns

If building in-house, these patterns avoid common mistakes.

Event-based consumption separates action tracking from energy deduction. Store user actions as events. Process energy changes asynchronously. This prevents blocking user actions on energy calculations but requires careful consistency management.

Scheduled regeneration jobs grant energy at fixed intervals. Cron jobs that run hourly or daily and grant energy to eligible users. This pattern is simple but creates load spikes. Trophy uses distributed scheduling that spreads regeneration load evenly.

Lazy regeneration computes energy only when queried. Store last check time. When user requests their balance, calculate regeneration since last check and update. This avoids scheduled jobs but complicates balance queries. Trophy uses hybrid approach with cached totals and lazy updates.

Optimistic locking prevents race conditions. Check energy balance, attempt consumption, verify balance didn't change during operation. If it changed, retry. This ensures consistency without blocking concurrent operations.

Denormalized balances for query performance. Maintain current energy in fast storage (Redis). Recompute from event history only when needed. Trophy caches current balances with millisecond query latency.

Trophy implements these patterns. You configure regeneration rules and consumption triggers. Trophy handles the infrastructure complexity.

Implementation Estimate

Here's realistic timeline for building energy systems in-house:

Week 1-2: Basic implementation. Track energy balance. Deduct for actions. Display totals. Works in development with simple cases.

Week 3-4: Regeneration logic. Implement time-based regeneration with scheduled jobs. Handle maximum caps. Make regeneration work across user sessions and time zones. Test edge cases around timing.

Week 5-6: Consumption triggers. Build system for deducting energy based on different actions. Implement variable consumption amounts. Handle insufficient energy cases gracefully.

Week 7: Concurrency and edge cases. Prevent race conditions. Handle rapid actions correctly. Test regeneration at scale. Fix performance issues.

Ongoing: Maintenance and tuning. As usage patterns change, regeneration rates need adjustment. New actions need consumption rules. This work continues indefinitely.

That's 7+ weeks of engineering time plus ongoing maintenance. Trophy's infrastructure eliminates this timeline, reducing implementation to 1 day to 1 week of integration work.

Building with Trophy

Trophy's integration is faster because energy infrastructure already exists. Here's what implementation looks like.

Step 1: Create Energy System

In Trophy's dashboard, create a points system called "Energy" (or your preferred name). Configure the maximum energy cap users can have. Trophy supports any maximum up to your requirements.

Energy systems are just points systems with specific regeneration and consumption rules. Trophy's flexible points infrastructure supports both XP-style accumulation and energy-style metering.

Step 2: Configure Regeneration Triggers

Set up how users gain energy over time. In Trophy's dashboard, create time-based triggers:

Hourly regeneration: Grant X energy every N hours

  • Award 1 energy every hour
  • Award 10 energy every 6 hours
  • Maximum caps prevent energy exceeding limits

Daily regeneration: Grant energy once per day

  • Award 20 energy at midnight user time
  • Award 50 energy every 24 hours
  • Trophy handles timezone timing automatically

Trophy's trigger system grants energy automatically based on your configuration. Users receive energy without manual processing.

Step 3: Configure Consumption Triggers

Set up how users spend energy. Create negative-value triggers for actions that consume energy:

Action-based consumption: Deduct energy when users perform specific actions

  • Deduct 1 energy per lesson viewed
  • Deduct 5 energy per workout started
  • Deduct 10 energy per premium feature access

Configure these through Trophy's dashboard as negative point awards. When users perform tracked actions, Trophy automatically deducts configured energy amounts.

Step 4: Track Energy-Consuming Actions

Send events for actions that consume energy:

import { TrophyApiClient } from '@trophyso/node';

const trophy = new TrophyApiClient(process.env.TROPHY_API_KEY);

// When user views a lesson (consumes 1 energy)
const response = await trophy.metrics.event('lesson_viewed', {
  user: {
    id: 'user-123'
  },
  value: 1 // 1 lesson viewed
});

// Check remaining energy
if (response.points?.energy) {
  const remaining = response.points.energy.total;
  const consumed = Math.abs(response.points.energy.added); // Will be negative
  console.log(`Consumed ${consumed} energy. ${remaining} remaining.`);
}

Trophy processes the event and automatically deducts energy based on trigger configuration. The response includes updated energy balance for immediate display.

Changes to energy consumption logic can be made in the Trophy dashboard, preventing back and forth code changes.

Step 5: Check Energy Before Actions

Before allowing energy-consuming actions, check if user has sufficient energy:

// Check user's current energy
const energy = await trophy.users.points('user-123', 'energy');

if (energy.total > 0) {
  // User has energy, allow action
  await performAction();
  
  // Track the action (consumes energy)
  await trophy.metrics.event('lesson_viewed', {
    user: { id: 'user-123' },
    value: 1
  });
} else {
  // User has no energy, prevent action or show paywall
  showInsufficientEnergyMessage();
}

This pattern prevents users from attempting actions they can't afford. The energy check happens before action processing, providing clear feedback.

Step 6: Display Energy Status

Show users their current energy and when it regenerates:

// Get detailed energy information
const energy = await trophy.users.points('user-123', 'energy', {
  awards: 5  // Last 5 energy changes
});

console.log({
  current: energy.total,
  maximum: energy.maximum,
  recentChanges: energy.awards.map(award => ({
    amount: award.points,
    trigger: award.trigger.name,
    time: award.timestamp
  }))
});

Trophy returns current energy, maximum cap, and recent energy changes. Use this data for UI showing energy status and regeneration timing. The points API documentation covers all available fields.

Regeneration Strategies

Different regeneration patterns serve different product goals.

Constant regeneration grants energy at fixed intervals regardless of usage. Users get 1 energy per hour even if they're at maximum. Simple but can waste potential energy when users hit caps.

Regeneration until cap stops when users reach maximum. Trophy's default behavior. Users don't waste regeneration but might feel pressure to spend energy before hitting cap.

Overflow to storage lets excess regeneration accumulate in separate pool. Complex but prevents waste. Trophy supports this through secondary points systems that have different caps.

Activity-based regeneration grants energy for specific actions beyond time. Complete a challenge, gain energy. This creates positive feedback loops where engagement grants resources for more engagement.

Trophy's time-based triggers handle first two patterns natively. Configure in dashboard without code. More complex patterns use multiple points systems or custom trigger logic.

Consumption Patterns

How you consume energy affects gameplay and user psychology.

Fixed consumption deducts the same amount for all instances of an action. 1 energy per lesson. Simple and predictable. Users understand cost clearly.

Variable consumption charges different amounts for different actions or contexts. 1 energy for basic lesson, 5 energy for advanced lesson. Creates strategic choice about energy spending.

Scaling consumption increases cost based on usage. First 5 lessons cost 1 energy each, next 5 cost 2 each. Encourages moderation and prevents grinding. Trophy implements through threshold-based triggers.

Partial refunds return energy if actions don't complete. User starts lesson (spends energy) but quits (refunds energy). Requires custom logic to track partial completions and issue refunds as positive point awards.

Trophy's trigger flexibility supports all these patterns. Configure consumption amounts through dashboard. Adjust based on player behavior without code changes.

Preventing Energy Gaming

Energy systems create incentives to game. Design prevents exploitation.

Maximum caps prevent infinite accumulation. Trophy's configurable maximum prevents users from stockpiling unlimited energy for later use. Choose caps based on intended session length.

Rate limiting beyond energy. If users can refresh energy artificially (time zone changes, system clock manipulation), add detection and rate limits. Trophy's server-side processing prevents client-side time manipulation.

Consumption verification ensures actions actually completed before deducting energy. Deduct energy only after verifying action succeeded. Trophy's event-based model supports this through proper event sequencing.

Account-level tracking prevents multi-account farming. If users create multiple accounts to bypass energy limits, implement account-level detection. Trophy tracks per-user; your authentication layer handles account limits.

Display and Communication

How you present energy affects user experience.

Clear cost indicators before actions. "This will cost 5 energy" prevents surprise when users can't afford actions. Trophy's balance checking enables this.

Regeneration timing transparency. "Energy regenerates in 2 hours" or "Full energy at 8 PM" gives users planning information. Trophy's time-based triggers have predictable schedules you can communicate.

Friendly empty states. "You're out of energy! It regenerates 1 per hour." explains situation without being punitive. Frame energy as pacing mechanic, not punishment.

Progress toward regeneration. "Energy: 3/10 (regenerating...)" shows both current state and that progress continues. Trophy's balance provides current amount; you track maximum for display.

Economic Tuning

Energy systems need careful tuning to feel fair without killing engagement.

Regeneration rate determines session frequency. Fast regeneration (hourly) encourages frequent short sessions. Slow regeneration (daily) encourages longer, less frequent sessions. Trophy makes rate adjustments through dashboard configuration.

Maximum cap determines session length. Cap of 10 with consumption of 1 per action allows 10 actions per session. Cap of 100 allows longer sessions but slower regeneration to full. Trophy's configurable cap lets you test different values.

Consumption amounts relative to regeneration define gameplay pace. If regeneration grants 20 energy daily and average session consumes 15, users can play daily with buffer. Trophy's analytics show consumption patterns informing tuning.

Monitor average energy levels across users. If most users sit at maximum constantly, regeneration is too generous or consumption too low. If most users sit at zero, consumption is too high or regeneration too slow. Trophy's analytics dashboard shows energy distribution.

Analytics and Optimization

Trophy provides analytics for energy system health.

Distribution curves show how energy spreads across users. Clustering at maximum suggests regeneration exceeds consumption. Clustering at zero suggests opposite problem.

Consumption patterns show which actions consume most energy. If one action dominates consumption, it might need rebalancing. Trophy's trigger analytics show consumption by trigger type.

Regeneration effectiveness shows how much granted energy gets used versus wasted. High waste (users constantly at cap) suggests tuning opportunities.

Session length correlation reveals whether energy gates usage appropriately. Do users stop playing because they're out of energy or for other reasons? Trophy's data combined with your session analytics answers this.

Use these insights to tune regeneration rates, consumption amounts, and maximum caps. Trophy's dashboard configuration makes adjustments quick without code changes.

Common Implementation Mistakes

Teams integrating Trophy make predictable errors.

Blocking critical paths on energy. Don't prevent onboarding or core value delivery with energy gates. Use energy for optional features or advanced content, not basic functionality.

Insufficient energy for meaningful sessions. If regeneration grants enough energy for 2 minutes of play, users can't engage meaningfully. Trophy's configurable caps let you test session lengths.

Unclear regeneration timing. Users should understand when energy returns. Trophy's time-based triggers have predictable schedules. Communicate these in your UI.

No emergency energy sources. Some products offer energy purchase or alternative earning. This creates escape valve for engaged users. Implement through your monetization layer; Trophy tracks the energy you grant.

Forgetting timezone impacts. Daily regeneration at midnight means different times for different users. Trophy handles this, but your UI should show user-local times.

Build vs. Buy Decision

Here's how to think about build versus buy for energy:

Build in-house when:

  • Your energy mechanics are so unusual platforms don't support them
  • You have backend engineers with capacity for 2-3 months plus maintenance
  • Engineering control over infrastructure is critical to your business
  • Scale is small enough that simple implementations work (under 1,000 users)

Use Trophy when:

  • You want energy features in days, not months
  • Time-based regeneration and metering are primary needs
  • Engineering time is better spent on core features
  • Tuning and rebalancing flexibility are important

Trophy's implementation guide covers the complete integration process. Most teams implement basic energy functionality in 1-2 days, advanced consumption patterns in 3-5 days. Compare this to 2-3 months building from scratch.

FAQ

How long does Trophy integration take for energy?

Basic energy tracking with regeneration and consumption: 1-2 days including trigger configuration and event tracking. Advanced features like variable consumption and complex metering: 3-5 days. Compare this to 2-3 months building in-house.

Can we adjust energy rates after launch?

Yes. Trophy's dashboard configuration means changing regeneration rates or consumption amounts requires no code deployment. Adjust trigger values and new events use new amounts.

How does Trophy prevent energy gaming?

Trophy's server-side processing prevents client-side time manipulation. Maximum caps prevent infinite accumulation. Your authentication layer handles multi-account detection. Trophy tracks per-user, not per-device.

What if we want different energy rates for different users?

Trophy's user attributes enable segment-specific triggers. Grant or consume different energy amounts based on subscription tier, user level, or other attributes. Configure through Trophy's dashboard.

Can users purchase energy?

Trophy tracks energy totals. Implementing purchases happens in your application through your payment provider. Grant purchased energy as positive point awards through Trophy's API.

How do we test energy changes without affecting real users?

Trophy supports multiple environments (staging, production). Test trigger configurations in staging before deploying to production. Trophy's deterministic processing means staging tests predict production behavior.

What happens if users are at maximum when regeneration fires?

Trophy's default behavior stops regeneration at maximum. Users don't exceed the cap. Alternative patterns (overflow to storage) require multiple points systems configured through Trophy's dashboard.


Free up to 100 users. No CC required.