A peak shaving algorithm is a deterministic or predictive control logic that orchestrates behind-the-meter (BTM) battery energy storage systems to discharge precisely when a facility's net load approaches a predefined threshold. By capping the maximum power drawn from the grid during a billing interval—typically 15 minutes—the algorithm directly reduces the demand charge, a tariff component based on the highest average power consumed, which can constitute 30-70% of a commercial electric bill.
Glossary
Peak Shaving Algorithm

What is Peak Shaving Algorithm?
A peak shaving algorithm is a control logic that dispatches battery energy storage to discharge during periods of highest site load, thereby reducing the maximum demand charge levied by the utility.
Advanced implementations utilize model predictive control (MPC) and machine learning-based load forecasting to anticipate peaks rather than reacting to them. The algorithm continuously solves an optimization problem, balancing battery state-of-charge, cycle-life degradation costs, and real-time load predictions to determine the optimal discharge schedule, ensuring sufficient stored energy is reserved to clip the highest forecasted demand spikes without prematurely depleting the asset.
Key Characteristics of Peak Shaving Algorithms
Peak shaving algorithms are deterministic control logics that dispatch battery energy storage to cap site-level demand, directly reducing costly utility demand charges. The following characteristics define their operational architecture.
Demand Charge Reduction Logic
The primary objective is minimizing the maximum average power drawn over a utility-defined demand interval (typically 15 minutes). The algorithm continuously monitors real-time site load against a configurable demand limit setpoint. When load approaches this threshold, the battery discharges to shave the peak. The logic must account for ratchet clauses, where a single peak can set charges for months, making precision critical.
Predictive vs. Reactive Control
Algorithms fall into two categories:
- Reactive Control: Triggers discharge based on real-time load exceeding a static threshold. Simple but can miss rapid load spikes.
- Predictive Control: Uses machine learning forecasting of site load and solar generation to pre-emptively charge the battery before predicted peaks. This ensures state of charge (SoC) availability and prevents premature depletion, maximizing demand reduction for complex load profiles.
State of Charge Management
The algorithm must maintain a delicate SoC reserve specifically for peak events. Discharging too early leaves no energy for the actual peak; holding too much reserve wastes opportunities for energy arbitrage. Advanced algorithms dynamically adjust the SoC target based on time-of-day, day-ahead load forecasts, and the probability of a peak event occurring within the next demand interval.
Constraint-Aware Optimization
Dispatch decisions are bounded by physical and contractual limits:
- Battery C-rate: Maximum charge/discharge power relative to capacity.
- Cycle life degradation: Marginal cost of cycling the battery versus the demand charge avoided.
- Export limitations: Utility rules preventing power export to the grid.
- Round-trip efficiency: Energy losses during charge/discharge cycles. The algorithm solves a constrained optimization problem, often using Model Predictive Control (MPC) , to find the economically optimal dispatch schedule.
Integration with Site Generation
Behind-the-meter solar photovoltaics introduce variability. A cloud passing over an array can cause a sudden drop in generation, creating an unexpected net load spike. The peak shaving algorithm must fuse real-time solar irradiance data and short-term generation forecasts to anticipate these dips. It pre-emptively reserves battery capacity to compensate for solar intermittency, ensuring the combined site import remains below the demand limit.
Utility Tariff Awareness
The algorithm's logic is fundamentally shaped by the specific utility rate structure. It must model:
- Time-of-Use (TOU) windows: When demand charges apply (e.g., 12 PM–6 PM weekdays).
- Non-coincident peaks: Charges based on the site's maximum demand regardless of system peak.
- Coincident peaks: Charges based on site demand during the grid's top 3-5 system peaks. The algorithm shifts from simple threshold shaving to strategic, calendar-driven dispatch based on tariff rules.
Frequently Asked Questions
Explore the core mechanics and operational logic behind the algorithms that dispatch battery energy storage to reduce costly demand charges and stabilize site-level electrical load.
A peak shaving algorithm is a control logic that dispatches a Battery Energy Storage System (BESS) to discharge precisely during periods of highest site load, thereby reducing the maximum power draw from the utility grid. The algorithm operates by continuously monitoring real-time facility load against a predefined demand limit threshold. When the total site consumption approaches or exceeds this setpoint, the controller calculates the exact discharge power required to 'shave' the excess load. This is typically achieved through a closed-loop Proportional-Integral (PI) controller or a more advanced Model Predictive Control (MPC) strategy that forecasts load spikes using historical data. The primary objective is not energy arbitrage but the reduction of demand charges, which are fees levied by utilities based on the highest 15-minute or 30-minute average power draw during a billing cycle. The algorithm must also manage the battery's State of Charge (SOC), ensuring sufficient reserve capacity is available for forecasted peak windows while respecting depth-of-discharge limits to preserve battery cycle life.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Peak shaving algorithms operate within a broader ecosystem of control strategies, optimization techniques, and grid services. These related concepts define the technical and economic context for battery dispatch logic.
Demand Charge Management
The primary economic driver behind peak shaving. Commercial and industrial utility tariffs include demand charges based on the highest 15-minute average power draw during a billing period. A peak shaving algorithm targets these specific intervals to minimize the ratchet clause that can lock in high charges for months. The algorithm must predict not just total energy consumption but the precise timing and magnitude of non-coincident peaks that may not align with overall grid stress.
Battery State of Charge (SoC) Management
The peak shaving algorithm must balance immediate discharge needs against long-term battery health. Key constraints include:
- Depth of Discharge (DoD): Limiting discharge to 80-90% to preserve cycle life
- C-rate limitations: Respecting maximum charge/discharge rates to prevent thermal stress
- SoC reservation: Holding sufficient charge for predicted afternoon peaks while avoiding full saturation
- Calendar fade compensation: Adjusting dispatch aggressiveness as the battery degrades over its 10-15 year lifespan
Load Forecasting Integration
Predictive accuracy determines peak shaving effectiveness. The algorithm ingests short-term load forecasts generated by machine learning models trained on historical interval meter data, weather inputs, and occupancy schedules. A 15-minute ahead forecast with less than 5% mean absolute percentage error (MAPE) is critical. The algorithm must also account for forecast uncertainty bands, maintaining a reserve buffer to handle unexpected load spikes that exceed predicted values.
Time-of-Use (TOU) Rate Arbitrage
While distinct from peak shaving, TOU arbitrage often runs concurrently on the same battery asset. The algorithm must coordinate these competing objectives:
- Peak shaving: Discharge triggered by site load exceeding a kW threshold
- TOU arbitrage: Discharge triggered by high energy prices ($/kWh)
- Conflict resolution: A hierarchical controller typically prioritizes demand charge reduction over energy arbitrage when the battery's power capacity is constrained
- Stacked services: Advanced algorithms co-optimize both revenue streams using multi-objective optimization
Model Predictive Control (MPC) Framework
The most sophisticated peak shaving algorithms use Model Predictive Control, which solves a constrained optimization problem over a receding time horizon. The MPC framework:
- Maintains a dynamic model of battery efficiency, thermal limits, and degradation
- Solves a mixed-integer linear program (MILP) at each time step to determine optimal charge/discharge power
- Incorporates updated load forecasts and real-time SoC feedback
- Applies only the first control action, then re-optimizes at the next interval This approach handles the non-linear degradation cost and discrete switching constraints that simpler rule-based controllers cannot address.
Grid Export Constraints
Peak shaving algorithms must respect interconnection agreements that often prohibit or limit power export to the grid. The controller enforces a zero-export constraint by dynamically limiting battery discharge to never exceed the site's instantaneous load. In jurisdictions allowing export, the algorithm may participate in demand response programs by discharging during utility-called events, but must carefully track export tariffs and net metering rules that affect the economic return of sending power back to the distribution system.

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us