Alerting: Add compressed periodic save for alert instances (#111803)

What is this feature?

This PR implements compressed periodic save for alert state storage, providing a more efficient alternative to regular periodic saves by grouping alert instances by rule UID and storing them using protobuf and snappy compression. When enabled via the state_compressed_periodic_save_enabled configuration option, the system groups alert instances by their alert rule, compresses each group using protobuf serialization and snappy compression, and processes all rules within a single database transaction at specified intervals instead of syncing after every alert evaluation cycle.

Why do we need this feature?

During discussions in PR #111357, we identified the need for a compressed approach to periodic alert state storage that could further reduce database load beyond the jitter mechanism. While the jitter feature distributes database operations over time, this compressed periodic save approach reduces the frequency of database operations by batching alert state updates at explicitly declared intervals rather than syncing after every alert evaluation cycle.
This approach provides several key benefits:

- Reduced Database Frequency: Instead of frequent sync operations tied to alert evaluation cycles, updates occur only at configured intervals
- Storage Efficiency: Rule-based grouping with protobuf and snappy compression significantly reduces storage requirements

The compressed periodic save complements the existing jitter mechanism by providing an alternative strategy focused on reducing overall database interaction frequency while maintaining data integrity through compression and batching.

Who is this feature for?

- Platform/Infrastructure teams managing large-scale Grafana deployments with high alert cardinality
- Organizations looking to optimize storage costs and database performance for alerting workloads
- Production environments with 1000+ alert rules where database write frequency is a concern
This commit is contained in:
Seunghun Shin
2025-11-07 11:51:48 +01:00
committed by GitHub
parent 589435b7c2
commit c784de6ef5
8 changed files with 330 additions and 42 deletions
@@ -9,6 +9,7 @@ import (
"time"
"github.com/golang/snappy"
"github.com/grafana/grafana/pkg/services/sqlstore"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/timestamppb"
@@ -98,28 +99,13 @@ func (st ProtoInstanceDBStore) SaveAlertInstancesForRule(ctx context.Context, ke
logger := st.Logger.FromContext(ctx)
logger.Debug("SaveAlertInstancesForRule called", "rule_uid", key.UID, "org_id", key.OrgID, "instances", len(instances))
alert_instances_proto := make([]*pb.AlertInstance, len(instances))
for i, instance := range instances {
alert_instances_proto[i] = alertInstanceModelToProto(instance)
}
compressedAlertInstances, err := compressAlertInstances(alert_instances_proto)
compressedAlertInstances, err := convertAndCompressAlertInstances(instances)
if err != nil {
return fmt.Errorf("failed to compress alert instances: %w", err)
}
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
params := []any{key.OrgID, key.UID, compressedAlertInstances, time.Now()}
upsertSQL := st.SQLStore.GetDialect().UpsertSQL(
"alert_rule_state",
[]string{"org_id", "rule_uid"},
[]string{"org_id", "rule_uid", "data", "updated_at"},
)
_, err = sess.SQL(upsertSQL, params...).Query()
return err
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
return st.upsertCompressedAlertInstances(sess, key.OrgID, key.UID, compressedAlertInstances, time.Now())
})
}
@@ -134,9 +120,68 @@ func (st ProtoInstanceDBStore) DeleteAlertInstancesByRule(ctx context.Context, k
}
func (st ProtoInstanceDBStore) FullSync(ctx context.Context, instances []models.AlertInstance, batchSize int, jitterFunc func(int) time.Duration) error {
if len(instances) == 0 {
return nil
}
logger := st.Logger.FromContext(ctx)
logger.Error("FullSync called and not implemented")
return errors.New("fullsync is not implemented for proto instance database store")
logger.Debug("FullSync called", "total_instances", len(instances))
ruleGroups := make(map[models.AlertRuleKeyWithGroup][]models.AlertInstance)
for _, instance := range instances {
ruleKey := models.AlertRuleKeyWithGroup{
AlertRuleKey: models.AlertRuleKey{
OrgID: instance.RuleOrgID,
UID: instance.RuleUID,
},
RuleGroup: "",
}
ruleGroups[ruleKey] = append(ruleGroups[ruleKey], instance)
}
type preparedRule struct {
ruleKey models.AlertRuleKeyWithGroup
compressedData []byte
}
preparedRules := make([]preparedRule, 0, len(ruleGroups))
for ruleKey, ruleInstances := range ruleGroups {
// Convert and compress instances
compressedAlertInstances, err := convertAndCompressAlertInstances(ruleInstances)
if err != nil {
logger.Error("Failed to compress instances for rule", "rule_uid", ruleKey.UID, "error", err)
continue
}
preparedRules = append(preparedRules, preparedRule{
ruleKey: ruleKey,
compressedData: compressedAlertInstances,
})
logger.Debug("Prepared rule for sync", "rule_uid", ruleKey.UID, "org_id", ruleKey.OrgID, "instances", len(ruleInstances))
}
return st.SQLStore.WithTransactionalDbSession(ctx, func(sess *sqlstore.DBSession) error {
syncTimestamp := time.Now()
logger.Debug("Starting FullSync transaction", "rules_count", len(preparedRules), "timestamp", syncTimestamp)
// First we delete all records from the table
if _, err := sess.Exec("DELETE FROM alert_rule_state"); err != nil {
return fmt.Errorf("failed to delete alert_rule_state: %w", err)
}
for i, prepared := range preparedRules {
logger.Debug("Executing UPSERT for rule", "rule_uid", prepared.ruleKey.UID, "org_id", prepared.ruleKey.OrgID, "rule_index", i+1, "total_rules", len(preparedRules))
// Execute UPSERT with pre-compressed data using helper method
if err := st.upsertCompressedAlertInstances(sess, prepared.ruleKey.OrgID, prepared.ruleKey.UID, prepared.compressedData, syncTimestamp); err != nil {
return fmt.Errorf("failed to save instances for rule %s: %w", prepared.ruleKey.UID, err)
}
}
logger.Debug("FullSync transaction completed successfully", "rules_synced", len(preparedRules))
return nil
})
}
func alertInstanceModelToProto(modelInstance models.AlertInstance) *pb.AlertInstance {
@@ -155,6 +200,30 @@ func alertInstanceModelToProto(modelInstance models.AlertInstance) *pb.AlertInst
}
}
// convertAndCompressAlertInstances converts model instances to protobuf and compresses them
func convertAndCompressAlertInstances(instances []models.AlertInstance) ([]byte, error) {
alertInstancesProto := make([]*pb.AlertInstance, len(instances))
for i, instance := range instances {
alertInstancesProto[i] = alertInstanceModelToProto(instance)
}
return compressAlertInstances(alertInstancesProto)
}
// upsertCompressedAlertInstances performs upsert operation for compressed alert instances
func (st ProtoInstanceDBStore) upsertCompressedAlertInstances(sess *sqlstore.DBSession, orgID int64, ruleUID string, compressedData []byte, timestamp time.Time) error {
upsertSQL := st.SQLStore.GetDialect().UpsertSQL(
"alert_rule_state",
[]string{"org_id", "rule_uid"},
[]string{"org_id", "rule_uid", "data", "updated_at"},
)
params := []any{orgID, ruleUID, compressedData, timestamp}
_, err := sess.SQL(upsertSQL, params...).Query()
return err
}
func compressAlertInstances(instances []*pb.AlertInstance) ([]byte, error) {
mProto, err := proto.Marshal(&pb.AlertInstances{Instances: instances})
if err != nil {