基于 SOC 职业分类
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/tools-only/X-Skills --skill implement-batch-processing命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
正在显示 SKILL.md
Index of Build Systems Skills
Coordination patterns for distributed dataflow systems including barriers, epochs, and distributed snapshots
Windowing, sessionization, time-series aggregation, and late data handling for streaming systems
| name | implement-batch-processing |
| description | Implement high-performance batch API operations with job queues, progress... |
| shortcut | btch |
| category | api |
| difficulty | intermediate |
| estimated_time | 2-4 hours |
| version | 2.0.0 |
Creates high-performance batch API processing infrastructure for handling bulk operations efficiently. Implements job queues with Bull/BullMQ, real-time progress tracking, transaction management, and intelligent error recovery. Supports millions of records with optimal resource utilization.
Use this command when:
Do NOT use this command for:
Before running this command, ensure:
The command examines your data processing needs:
Sets up Bull/BullMQ for reliable job processing:
Implements RESTful endpoints for batch operations:
Creates efficient batch processing workflows:
Integrates comprehensive monitoring:
The command generates a complete batch processing system:
batch-processing/
├── src/
│ ├── queues/
│ │ ├── batch-queue.js
│ │ ├── workers/
│ │ │ ├── batch-processor.js
│ │ │ └── chunk-worker.js
│ │ └── jobs/
│ │ ├── import-job.js
│ │ └── export-job.js
│ ├── api/
│ │ ├── batch-controller.js
│ │ └── batch-routes.js
│ ├── services/
│ │ ├── batch-service.js
│ │ ├── validation-service.js
│ │ └── transaction-manager.js
│ └── utils/
│ ├── chunking.js
│ └── progress-tracker.js
├── config/
│ └── queue-config.js
├── tests/
│ └── batch-processing.test.js
└── docs/
└── batch-api.md
Scenario: Import 100,000 users from CSV with validation and deduplication
Generated Implementation:
// queues/batch-queue.js
import Queue from 'bull';
import Redis from 'ioredis';
const batchQueue = new Queue('batch-processing', {
redis: {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT
},
defaultJobOptions: {
removeOnComplete: 100,
removeOnFail: 500,
attempts: 3,
backoff: {
type: 'exponential',
delay: 2000
}
}
});
// api/batch-controller.js
class BatchController {
async createBatchJob(req, res) {
const { type, data, options = {} } = req.body;
// Validate batch request
if (!this.validateBatchRequest(type, data)) {
return res.status(400).json({
error: 'Invalid batch request'
});
}
// Create job with unique ID
jobId = ;
job = batchQueue.(type, {
data,
: req..,
: {
: options. || ,
: options. !== ,
: options. || ,
...options
}
}, {
jobId,
: options. ||
});
res.().({
: job.,
: ,
: .(data.),
: ,
:
});
}
() {
{ jobId } = req.;
job = batchQueue.(jobId);
(!job) {
res.().({ : });
}
state = job.();
progress = job.();
res.({
: job.,
: state,
: {
: progress. || ,
: progress. || ,
: progress. || ,
: progress. || ,
: progress. || ,
: progress. || ,
: progress. ||
},
: job.,
: job.,
: job.,
: state === ? job. :
});
}
}
{
() {
.();
}
() {
batchQueue.(, (job) => {
{ data, options } = job.;
chunks = .(data, options.);
results = {
: [],
: [],
: []
};
job.({
: ,
: data.,
: chunks.,
: ,
: ,
:
});
( i = ; i < chunks.; i++) {
chunk = chunks[i];
{
chunkResults = .(
chunk,
options,
job
);
results..(...chunkResults.);
results..(...chunkResults.);
results..(...chunkResults.);
processed = (i + ) * options.;
job.({
: .(, (processed / data.) * ),
: .(processed, data.),
: data.,
: results..,
: results..,
: i + ,
: chunks.
});
(options. && results.. > ) {
;
}
} (error) {
.(, error);
(options.) {
error;
}
chunk.( {
results..({
: item,
: error.
});
});
}
}
.(job., results);
{
: {
: data.,
: results..,
: results..,
: results..
},
: job.
};
});
}
() {
results = {
: [],
: [],
: []
};
trx = db.();
{
( item chunk) {
{
(options.) {
validation = .(item);
(!validation.) {
results..({
: item,
: validation.
});
;
}
}
existing = ()
.(, item.)
.();
(existing) {
(options.) {
results..({
: item,
:
});
;
} (options.) {
()
.(, item.)
.(item);
results..({
: ,
: existing.,
: item
});
;
}
}
[userId] = ().({
...item,
: (),
: job.
});
results..({
: ,
: userId,
: item
});
} (error) {
results..({
: item,
: error.
});
}
}
trx.();
} (error) {
trx.();
error;
}
results;
}
() {
chunks = [];
( i = ; i < array.; i += size) {
chunks.(array.(i, i + size));
}
chunks;
}
}
Scenario: Export millions of records with streaming and compression
Generated Streaming Export:
// services/export-service.js
import { Transform } from 'stream';
import zlib from 'zlib';
class ExportService {
async createExportJob(query, format, options) {
const job = await batchQueue.add('data-export', {
query,
format,
options
});
return job;
}
async processExportJob(job) {
const { query, format, options } = job.data;
// Create export stream
const exportStream = this.createExportStream(query, format);
const outputPath = `/tmp/exports/${job.id}.${format}.gz`;
// Create compression stream
const gzip = zlib.createGzip();
const writeStream = fs.createWriteStream(outputPath);
let recordCount = 0;
let errorCount = 0;
return new Promise((resolve, reject) => {
exportStream
.pipe(new Transform({
() {
recordCount++;
(recordCount % === ) {
job.({
: recordCount,
: .(, (recordCount / options.) * )
});
}
(, chunk);
}
}))
.(gzip)
.(writeStream)
.(, () => {
url = .(outputPath, job.);
({
recordCount,
errorCount,
: url,
: (.() + * * * )
});
})
.(, reject);
});
}
() {
stream = db.(query).();
(format) {
:
stream.(.());
:
stream.(.());
:
stream.(.());
:
();
}
}
}
Scenario: Process API calls with rate limiting and retry logic
Generated Rate-Limited Processor:
// workers/rate-limited-processor.js
import Bottleneck from 'bottleneck';
class RateLimitedProcessor {
constructor() {
// Configure rate limiter: 10 requests per second
this.limiter = new Bottleneck({
maxConcurrent: 5,
minTime: 100 // 100ms between requests
});
}
async processBatch(job) {
const { items, apiEndpoint, options } = job.data;
const results = [];
// Process items with rate limiting
const promises = items.map((item, index) =>
this.limiter.schedule(async () => {
try {
const result = await this.callAPI(apiEndpoint, item);
// Update progress
await job.progress({
processed: index + 1,
total: items.length,
percentage: ((index + 1) / items.) *
});
{ : , : result };
} (error) {
{
: ,
: error.,
item
};
}
})
);
results = .(promises);
{
: results.( r.).,
: results.( !r.),
: items.
};
}
}
Symptoms: Jobs not processing, Redis connection errors Cause: Redis server unavailable or misconfigured Solution:
batchQueue.on('error', (error) => {
console.error('Queue error:', error);
// Implement fallback or alerting
});
Prevention: Implement Redis Sentinel or cluster for high availability
Symptoms: Process crashes with heap out of memory Cause: Processing chunks too large for available memory Solution: Reduce chunk size and implement streaming
Symptoms: Batch processing hangs or fails with deadlock errors Cause: Concurrent transactions competing for same resources Solution: Implement retry logic with exponential backoff
--chunk-size/batch --chunk-size 500--concurrency/batch --concurrency 10--retry-attempts/batch --retry-attempts 5✅ DO:
❌ DON'T:
💡 TIPS:
/api-rate-limiter - Implement API rate limiting/api-event-emitter - Event-driven processing/api-monitoring-dashboard - Monitor batch jobs/database-bulk-operations - Database-level batch operations⚠️ Security Considerations:
Solution: Check worker processes and Redis connectivity
Solution: Increase chunk size and worker concurrency
Solution: Review validation logic and add retry mechanisms
Last updated: 2025-10-11 Quality score: 9.5/10 Tested with: Bull 4.x, BullMQ 3.x, Redis 7.0