How to Build a Reliable AI Music Workflow in n8n with ACE Music

Build a Reliable AI Music Workflow in n8n with ACE Music

AI music generation is a natural fit for n8n: accept an idea, submit it to a music API, wait for the tracks, and send the results to storage or another application.

The difficult part is not making the first request. It is making the workflow safe when:

  • Generation takes several minutes.
  • An HTTP request times out after reaching the provider.
  • n8n restarts while a task is processing.
  • An execution is retried.
  • Two workflow runs receive the same business request.
  • One track succeeds while another candidate fails.
  • Polling encounters temporary rate limits.

A production workflow must treat music generation as an asynchronous state machine, not as one long HTTP request.

This tutorial builds that state machine using ACE Music, n8n’s HTTP Request and Wait nodes, durable task records, stable idempotency keys, and a recovery path for interrupted executions.

What You Will Build

The finished workflow follows this path:

Trigger
  ↓
Prepare request and stable operation ID
  ↓
Look up an existing task
  ├─ Existing task → resume polling
  └─ No task       → create ACE Music task
                         ↓
                  persist task_id immediately
                         ↓
Wait → Get Task → terminal?
  ↑          └── no ─────┘
  └───────────────
                   yes
                    ↓
      save outputs or handle failure

The crucial detail is the recovery path:

Load unfinished task → Get Task

It bypasses task creation. Restarting a workflow must not automatically create another paid generation.

The reliable asynchronous polling and recovery loop

Prerequisites

You will need:

  1. An n8n instance.
  2. An Ace Data Cloud API key authorized for ACE Music.
  3. A durable store such as PostgreSQL, MySQL, Redis, an n8n Data Table, or another database.
  4. An HTTPS destination if generated files will be copied to your own storage.

Keep the API key in an n8n credential. Do not place it directly in a Code node, workflow name, expression, or exported workflow JSON.

ACE Music requests use Bearer authentication:

Authorization: Bearer YOUR_API_KEY

Understand the ACE Music Lifecycle

Music creation is submitted with:

POST https://api.acedata.cloud/acemusic/audios

Task retrieval uses:

POST https://api.acedata.cloud/acemusic/tasks

A successful asynchronous submission establishes a task. It does not mean the audio is ready. The returned task_id must be retained and used to retrieve the final result.[^1]

Relevant task states include:

created
submitting
processing
storing
submission_unknown
succeeded
partial_failed
failed

Treat these states as three groups:

Group Statuses Workflow behavior
Active created, submitting, processing, storing Wait and poll again
Uncertain submission_unknown Preserve the task and investigate; do not automatically create a replacement
Terminal succeeded, partial_failed, failed Stop polling and process the result

The task endpoint is free to query, and the ACE Music documentation recommends polling at intervals with gradual backoff. Completed audio tracks are returned in response.data.[^2]

Step 1: Design a Durable Task Record

Create one durable record for every logical music request.

A practical PostgreSQL schema is:

CREATE TABLE ace_music_jobs (
  operation_id       TEXT PRIMARY KEY,
  idempotency_key    TEXT NOT NULL UNIQUE,
  task_id            TEXT UNIQUE,
  request_hash       TEXT NOT NULL,
  request_body       JSONB NOT NULL,
  status             TEXT NOT NULL,
  poll_count         INTEGER NOT NULL DEFAULT 0,
  next_poll_at       TIMESTAMPTZ,
  response_body      JSONB,
  error_body         JSONB,
  created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at         TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

Each field has a separate responsibility:

  • operation_id identifies the business operation.
  • idempotency_key protects the provider-side submission.
  • task_id identifies the accepted ACE Music task.
  • request_hash detects reuse of an operation ID with a different payload.
  • status lets a recovery workflow find unfinished tasks.
  • poll_count supports bounded or progressive polling.
  • next_poll_at prevents the recovery process from polling too quickly.
  • response_body preserves the final result.
  • error_body retains failure details for investigation.

Do not rely only on transient data flowing between n8n nodes. Save the task externally as soon as the create request returns.

Step 2: Generate a Stable Operation ID

A random value generated every time a node runs is not a reliable idempotency key. A retry would generate a new value and appear to be a new request.

Whenever possible, derive the operation ID from an immutable upstream identifier:

const source = $json.order_id || $json.request_id;

if (!source) {
  throw new Error('A stable upstream request ID is required');
}

return [{
  json: {
    ...$json,
    operation_id: `music:${source}`,
    idempotency_key: `music:${source}`,
  }
}];

If no upstream identifier exists, create a UUID once and persist it before the paid API call:

const operationId = crypto.randomUUID();

return [{
  json: {
    ...$json,
    operation_id: operationId,
    idempotency_key: `music:${operationId}`,
  }
}];

Never regenerate this key when retrying the same logical operation.

ACE Music returns the original task when the same Idempotency-Key is reused with the same request content. Reusing a key with different request content produces a conflict.[^1]

Step 3: Build the Generation Payload

For an inspiration-mode generation:

{
  "action": "generate",
  "model": "acemusic-v1.1",
  "custom": false,
  "prompt": "Warm cinematic electronic music for a product launch, instrumental, optimistic, gradual build",
  "async": true
}

For a custom song:

{
  "action": "generate",
  "model": "acemusic-v1.1",
  "custom": true,
  "title": "Signals in the Night",
  "lyric": "[Verse]\nCity lights are drawing lines\n[Chorus]\nWe turn the signal into sound",
  "style": "cinematic synth-pop, warm vocal, restrained drums",
  "async": true
}

ACE Music also supports upload, cover, and mashup.

Generation, cover, and mashup operations normally produce two candidates. A successful reference upload returns one track.[^1]

Step 4: Check for an Existing Operation Before Submitting

Before the Create Task node, query your job table:

SELECT *
FROM ace_music_jobs
WHERE operation_id = $1
LIMIT 1;

Route the result through an If or Switch node:

No record
  → create pending record
  → submit to ACE Music

Record with task_id and non-terminal status
  → resume Get Task

Record with succeeded/partial_failed/failed
  → return stored result

Record without task_id
  → reconcile carefully
  → do not assume submission never happened

Use an atomic insert or upsert to prevent two simultaneous executions from both becoming the owner:

INSERT INTO ace_music_jobs (
  operation_id,
  idempotency_key,
  request_hash,
  request_body,
  status
)
VALUES ($1, $2, $3, $4, 'prepared')
ON CONFLICT (operation_id) DO NOTHING;

Read the row again after the insert. Only the execution that owns the operation should continue to the submission node.

Step 5: Configure the Create Task HTTP Request Node

Configure an n8n HTTP Request node with these settings:

  • Method: POST
  • URL: https://api.acedata.cloud/acemusic/audios
  • Authentication: Header Auth or Bearer credential
  • Send Headers: Enabled
  • Content-Type: application/json
  • Idempotency-Key: ={{ $json.idempotency_key }}
  • Send Body: JSON
  • Body: ={{ $json.request_body }}

The equivalent cURL request is:

curl --request POST \
  'https://api.acedata.cloud/acemusic/audios' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --header 'Idempotency-Key: music:order-8427' \
  --data '{
    "action": "generate",
    "model": "acemusic-v1.1",
    "custom": false,
    "prompt": "Warm cinematic electronic instrumental for a product launch",
    "async": true
  }'

Do not enable an unrestricted Retry on Fail policy on this paid submission node.

A timeout can mean either:

  1. ACE Music never received the request.
  2. ACE Music accepted the request, but n8n did not receive the response.

Only a stable idempotency key makes those two possibilities safe to reconcile.

Step 6: Persist the Task ID Immediately

The next node after Create Task should be a database update—not a notification, transformation, or optional branch.

Conceptually:

UPDATE ace_music_jobs
SET
  task_id = $2,
  status = 'created',
  response_body = $3,
  updated_at = NOW()
WHERE operation_id = $1;

A Code node can validate and normalize the submission response first:

const taskId =
  $json.task_id ??
  $json.id ??
  $json.data?.task_id;

if (!taskId) {
  throw new Error(
    'ACE Music submission returned without a recognizable task_id'
  );
}

return [{
  json: {
    operation_id: $('Prepare Request').item.json.operation_id,
    idempotency_key: $('Prepare Request').item.json.idempotency_key,
    task_id: taskId,
    status: 'created',
    submission_response: $json
  }
}];

Adjust the extraction expression to the response envelope returned by the current API version. Do not silently continue if the task identifier is missing.

Step 7: Add the Wait and Get Task Loop

Add a Wait node configured to resume after a time interval.

A simple starting interval is 15–30 seconds. The n8n Wait node pauses an execution and, when applicable, stores its execution data in the database before resuming.[^3]

One operational nuance is important: waits shorter than 65 seconds may remain in process rather than being offloaded to the database. If minimizing active process time is more important than rapid updates, use an interval of at least 65 seconds.[^3]

Configure the Get Task HTTP Request node as follows:

  • Method: POST
  • URL: https://api.acedata.cloud/acemusic/tasks
  • Authentication: The same Bearer credential
  • Content-Type: application/json
  • Body:
{
  "action": "retrieve",
  "id": "={{ $json.task_id }}"
}

The equivalent cURL request is:

curl --request POST \
  'https://api.acedata.cloud/acemusic/tasks' \
  --header 'Authorization: Bearer YOUR_API_KEY' \
  --header 'Content-Type: application/json' \
  --data '{
    "action": "retrieve",
    "id": "YOUR_TASK_ID"
  }'

Step 8: Route the Result by Status

Normalize the task response in a Code node:

const task = $json.data ?? $json;
const status = task.status ?? task.state;

const active = new Set([
  'created',
  'submitting',
  'processing',
  'storing'
]);

const terminal = new Set([
  'succeeded',
  'partial_failed',
  'failed'
]);

return [{
  json: {
    ...task,
    task_id: task.id ?? task.task_id,
    normalized_status: status,
    is_active: active.has(status),
    is_uncertain: status === 'submission_unknown',
    is_terminal: terminal.has(status)
  }
}];

Then route the result through a Switch node:

is_active = true
  → update checkpoint
  → Wait
  → Get Task

normalized_status = submission_unknown
  → persist state
  → alert or reconciliation queue

is_terminal = true
  → terminal handler

anything else
  → unknown-status handler

An unknown status should not enter an unlimited fast loop. Save the raw response and raise an operational alert.

Step 9: Use Backoff and a Polling Deadline

A fixed interval is easy to implement, but progressive polling is friendlier to the API.

For example:

const pollCount = ($json.poll_count ?? 0) + 1;

const schedule = [
  15,
  15,
  30,
  30,
  60,
  60,
  120,
  120,
  300
];

const waitSeconds =
  schedule[Math.min(pollCount - 1, schedule.length - 1)];

return [{
  json: {
    ...$json,
    poll_count: pollCount,
    wait_seconds: waitSeconds
  }
}];

Set the Wait node amount to:

={{ $json.wait_seconds }}

Also establish a polling deadline:

const startedAt = new Date($json.created_at).getTime();
const ageMinutes = (Date.now() - startedAt) / 60000;
const deadlineMinutes = 45;

return [{
  json: {
    ...$json,
    polling_deadline_reached: ageMinutes > deadlineMinutes
  }
}];

Reaching the deadline should stop the current execution and leave the task recoverable.

It should not:

  • Mark the ACE Music task as failed.
  • Generate a new idempotency key.
  • Create a replacement task automatically.
  • Assume that a delayed task will never complete.

Step 10: Handle Terminal Results Correctly

On succeeded, read the tracks from:

$json.response?.data

A defensive extractor could look like this:

const tracks = $json.response?.data ?? [];

const delivered = tracks.filter(track =>
  Boolean(track.audio_url) &&
  ['succeeded', 'completed', 'ready'].includes(
    track.state ?? 'succeeded'
  )
);

return delivered.map(track => ({
  json: {
    task_id: $json.task_id,
    track_id: track.id,
    title: track.title,
    duration_seconds: track.duration,
    audio_url: track.audio_url,
    image_url: track.image_url ?? null,
    lyric: track.lyric ?? null,
    style: track.style ?? null
  }
}));

Do not treat an HTTP 200 from Get Task as proof that music generation succeeded. It only proves that the retrieval request succeeded.

Handling partial_failed

For a partially failed generation:

  • Preserve every completed track.
  • Record the group as partially failed.
  • Store the public error details.
  • Do not automatically submit a replacement group.
  • Decide whether a human should review the usable output.

Handling failed

For a failed generation:

  • Save the error object.
  • Record the task_id and trace_id.
  • Apply policy based on the cause.
  • Do not assume every failure is safely retryable.
  • Do not create another paid task without determining whether it represents a new logical operation.

Recovering Interrupted Workflows

Use a separate scheduled recovery workflow.

Recovery Query

Run a query every few minutes:

SELECT *
FROM ace_music_jobs
WHERE status IN (
  'created',
  'submitting',
  'processing',
  'storing',
  'submission_unknown'
)
AND (
  next_poll_at IS NULL OR
  next_poll_at <= NOW()
)
ORDER BY updated_at ASC
LIMIT 100;

For every returned record:

Load record
  → Get Task using stored task_id
  → normalize status
  → Wait again or finish

The recovery workflow must not call Create Task for a record that already has a task_id.

If a record has an idempotency key but no task ID, classify it as an uncertain submission.

Possible responses include:

  1. Inspect the original n8n execution.
  2. Consult the API usage records.
  3. Reconcile using the same idempotency key and identical payload if your operational policy permits it.
  4. Contact support with the operation ID and trace information.

Do not generate a new key and resubmit automatically.

Why n8n Execution Retry Is Not Enough

n8n retries a failed execution from saved execution state, and completed nodes are generally not rerun.

However, the failed node receives its saved input again and may repeat side effects for items it processed before failing. Each retry also creates a new execution.[^4]

This distinction matters:

  • A failure after Create Task completed may resume after submission.
  • A failure inside Create Task after ACE Music accepted the request has an uncertain outcome.
  • Manually running the workflow again from its trigger can repeat every downstream side effect.
  • Retrying a failed Execute Sub-workflow node can run the entire sub-workflow again.

API-level idempotency and durable checkpoints are therefore still necessary.

Safe Retry Matrix

Situation Safe response
Validation error before sending Fix the payload and submit as a new intentional operation
HTTP 401 or 403 Fix credentials or permissions; keep the same logical operation
HTTP 402 Resolve the balance issue; do not loop
HTTP 409 Compare the key and payload; do not switch keys automatically
HTTP 429 on Get Task Wait and poll again
HTTP 429 on Create Task Retry only under a stable idempotency policy
Network timeout during Create Task Treat the result as uncertain; never assume the request failed
processing for a long time Continue bounded polling or hand off to recovery
submission_unknown Preserve the task identity and escalate reconciliation
partial_failed Keep completed outputs; do not blindly replace the group
failed Inspect the error and policy before creating a new operation

Observability Recommendations

Save these values with every job:

{
  "operation_id": "music:order-8427",
  "idempotency_key": "music:order-8427",
  "task_id": "platform-task-id",
  "n8n_execution_id": "12345",
  "status": "processing",
  "poll_count": 4,
  "last_polled_at": "2026-11-17T10:30:00Z",
  "trace_id": "trace-if-returned"
}

Useful alerts include:

  • An uncertain submission older than a defined threshold.
  • An active task with no successful poll for 15 minutes.
  • An unknown task status.
  • Repeated 401, 402, 403, or 429 responses.
  • A terminal response with no deliverable audio.
  • A conflicting request hash for an existing operation.
  • Two executions attempting to own the same operation ID.

Optional Callback Architecture

ACE Music accepts an optional HTTPS callback_url. A callback can reduce polling, but it should not eliminate task retrieval.

A robust hybrid design is:

Submit task with callback_url
  ↓
Persist task_id
  ↓
Wait for callback or scheduled reconciliation
  ↓
Retrieve authoritative task
  ↓
Process terminal result

Callback deliveries may be repeated, so deduplicate them by task_id.

A callback receiver should acknowledge the request quickly and move expensive processing into another workflow. If callback delivery fails, the original task should still be retrievable through the task endpoint.[^1]

Production Checklist

Before activating the workflow, verify that:

  • The API key is stored in an n8n credential.
  • Every logical request receives one stable operation ID.
  • The idempotency key is persisted before submission.
  • The payload hash is stored with the key.
  • An atomic insert prevents concurrent duplicate owners.
  • The task_id is saved immediately after acceptance.
  • Get Task—not Create Task—is inside the polling loop.
  • The recovery path bypasses Create Task.
  • Active, uncertain, partial, failed, and successful states are distinct.
  • Polling uses a delay, backoff, and a deadline.
  • Polling stops when the task reaches a terminal state.
  • Completed outputs are retained after a partial failure.
  • Paid POST requests do not use blind retries.
  • Logs contain operation, task, execution, and trace identifiers.
  • Unknown states generate an alert instead of an infinite loop.
  • Manual rerun procedures are documented.

Frequently Asked Questions

How often should n8n poll ACE Music?

Start at 15–30 seconds and gradually increase the interval.

If you want the Wait node to offload execution data instead of keeping short waits in process, use an interval of at least 65 seconds.[^3]

Should I retry the generation request if it times out?

Do not retry it with a new key.

A timeout does not prove that ACE Music rejected the request. Preserve the original idempotency key and task identity, then reconcile the original operation.

What is the difference between task_id and an audio ID?

The task_id identifies the asynchronous operation.

Audio IDs inside response.data identify delivered tracks. Those track IDs may later be used as references for operations such as cover or mashup.

Can I recover after n8n restarts?

Yes—provided that the idempotency key and task ID are stored outside transient execution memory.

A scheduled recovery workflow can reload unfinished records and continue from Get Task.

Is an HTTP 200 response from Get Task a successful song?

No.

It means the task retrieval request succeeded. You must still inspect the task status and the completed tracks inside response.data.

How do I prevent two n8n executions from creating the same task?

Use a stable business-level operation ID and an atomic database insert, unique constraint, or lock.

Only the execution that successfully claims the operation should be allowed to call Create Task.

Should the recovery workflow ever call Create Task?

Not for a record that already contains a task_id.

The recovery workflow should retrieve and observe the existing task. Task creation belongs only in the initial submission path.

Conclusion

A reliable n8n AI music workflow is not merely:

HTTP Request → Wait → Download

It is a recoverable protocol:

Stable operation identity
  → idempotent submission
  → immediate task persistence
  → delayed task retrieval
  → explicit terminal handling
  → durable recovery

Once task creation and task observation are treated as separate phases, browser refreshes, worker restarts, network uncertainty, and manual retries become manageable operational events instead of reasons to pay for duplicate generations.

The same architecture is useful beyond music. It provides a strong foundation for reliable image, video, rendering, transcription, and other long-running AI workflows.

References

[^1]: ACE Music Songs and Reference Audio API — request formats, idempotency, callbacks, outputs, pricing behavior, and recovery guidance.

[^2]: ACE Music Tasks and History API — task retrieval, statuses, polling, history, partial failures, and output delivery.

[^3]: n8n Wait node documentation — execution pausing, persistence, resume conditions, and behavior for intervals shorter than 65 seconds.

[^4]: n8n: Retry failed workflows — saved execution state, retry behavior, repeated side effects, and sub-workflow considerations.