crowdsecurity/crowdsec · error

error creating transaction: %w

Error message

error creating transaction: %w

What it means

AddToAllowlist groups item inserts in a single ent transaction via c.Ent.Tx(ctx). If the transaction client cannot be created (the driver fails to begin a transaction), the error is wrapped as 'error creating transaction: %w'. Nothing has been written at this point.

Source

Thrown at pkg/database/allowlists.go:142

	}

	result, err := q.First(ctx)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (c *Client) AddToAllowlist(ctx context.Context, list *ent.AllowList, items []*models.AllowlistItem) (int, error) {
	added := 0

	c.Log.Debugf("adding %d values to allowlist %s", len(items), list.Name)
	c.Log.Tracef("values: %+v", items)

	txClient, err := c.Ent.Tx(ctx)
	if err != nil {
		return 0, fmt.Errorf("error creating transaction: %w", err)
	}

	for _, item := range items {
		c.Log.Debugf("adding value %s to allowlist %s", item.Value, list.Name)

		rng, err := csnet.NewRange(item.Value)
		if err != nil {
			c.Log.Error(err)
			continue
		}

		query := txClient.AllowListItem.Create().
			SetValue(item.Value).
			SetIPSize(int64(rng.Size())).
			SetStartIP(rng.Start.Addr).
			SetStartSuffix(rng.Start.Sfx).
			SetEndIP(rng.End.Addr).
			SetEndSuffix(rng.End.Sfx).

View on GitHub (pinned to 909b515798)

Solutions

  1. Inspect the wrapped driver error; fix connectivity/pool issues (increase max connections, close leaked connections)
  2. Ensure the passed context is not already cancelled/timed out before calling
  3. For SQLite lock contention, reduce concurrent writers or migrate to MySQL/PostgreSQL
  4. Retry the add after the transient DB issue clears
Defensive patterns

Strategy: retry

Validate before calling

if err := ctx.Err(); err != nil { return fmt.Errorf("context already cancelled: %w", err) }

Try / catch

added, err := client.AddToAllowlist(ctx, list, items)
if err != nil && strings.Contains(err.Error(), "error creating transaction") {
    // transient DB issue: retry with backoff
    time.Sleep(backoff)
    added, err = client.AddToAllowlist(ctx, list, items)
}

Prevention

When it happens

Trigger: Client.AddToAllowlist called when the underlying DB connection is broken, the driver does not support transactions as configured, the context is already cancelled, or the connection pool is exhausted.

Common situations: SQLite 'database is locked' under concurrent LAPI writes; MySQL 'max_connections' exhausted; context deadline exceeded from an upstream API timeout; DB restarted mid-operation during a console allowlist import.

Understand the failure class

Background: Database query failed: Internal Server Error 500s wrapping SQL, Prisma, and connection failures — what to check first — this error's family across 16 libraries.

Related errors


AI-assisted analysis of crowdsecurity/crowdsec@909b515798 (2026-09-06). Data as JSON: /api/errors/3287d9f50d4ac9a9. Report an issue: GitHub.