xiaohongshu
xiaohongshu
Full skill instructions
gRPC (Google Remote Procedure Call) เป็น high-performance, open-source universal RPC framework ที่ใช้ Protocol Buffers สำหรับ serialization เหมาะสำหรับ microservices communication โดยให้ efficient binary serialization, streaming capabilities และ built-in code generation
gRPC ประกอบด้วย:
ผลกระทบทางธุรกิจ:
มุมมองด้านผลิตภัณฑ์:
gRPC ประกอบด้วย:
┌─────────────────────────────────────────────────────────┐
│ gRPC Architecture │
├─────────────────────────────────────────────────────────┤
│ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Client Layer │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │
│ │ │ Node.js │ │ Go │ │ Python │ │ │
│ │ │ Client │ │ Client │ │ Client │ │ │
│ │ └─────────────┘ └─────────────┘ └───────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ gRPC Client Layer │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │
│ │ │ Stub │ │ Channel │ │Interceptor│ │ │
│ │ │ Generated │ │ Management │ │ │ │ │
│ │ └─────────────┘ └─────────────┘ └───────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Network Layer (HTTP/2) │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │
│ │ │Multiplexing │ │Compression │ │Binary Frame│ │ │
│ │ └─────────────┘ └─────────────┘ └───────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ gRPC Server Layer │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │
│ │ │ Service │ │Interceptor │ │ Handler │ │ │
│ │ │ Registry │ │ Chain │ │ Logic │ │ │
│ │ └─────────────┘ └─────────────┘ └───────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────────────────────────┐ │
│ │ Data Layer │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌───────────┐ │ │
│ │ │ Database │ │ Cache │ │ External │ │ │
│ │ │ │ │ │ │ Services │ │ │
│ │ └─────────────┘ └─────────────┘ └───────────┘ │ │
│ └───────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘
| Tool | Purpose | Enterprise Features |
|---|---|---|
| protoc | Protocol Buffer compiler | Multi-language code generation |
| @grpc/grpc-js | Node.js gRPC runtime | Production-ready, streaming support |
| grpc-go | Go gRPC runtime | High performance, built-in load balancing |
| grpcio | Python gRPC runtime | Async support, interceptors |
| Envoy | gRPC-Web proxy | HTTP/1.1 to HTTP/2 translation |
| Consul | Service discovery | Health checks, DNS-based discovery |
// grpc-server.config.js
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = './proto/user_service.proto';
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const userProto = grpc.loadPackageDefinition(packageDefinition).user.v1;
const server = new grpc.Server();
server.addService(userProto.UserService.service, userService);
server.bindAsync(
'0.0.0.0:50051',
grpc.ServerCredentials.createInsecure(),
(error, port) => {
if (error) {
console.error('Failed to start server:', error);
return;
}
console.log(`Server running on port ${port}`);
}
);
Total Cost = (Server Cost) + (Network Cost) + (Storage Cost)
Server Cost = (Instance Hours × Hourly Rate)
Network Cost = (Data Transfer × Cost Per GB)
Storage Cost = (Proto Storage × Cost Per GB)
gRPC Optimization Savings:
- Bandwidth reduction: 50-70% (vs JSON)
- Latency reduction: 30-50% (HTTP/2 multiplexing)
- CPU reduction: 20-30% (binary serialization)
| Metric | Target | Measurement |
|---|---|---|
| RPC Latency | < 50ms | p95 latency |
| Throughput | > 10,000 RPS | Requests per second |
| Error Rate | < 0.01% | Total errors / Total requests |
| Connection Pool Utilization | < 80% | Active connections / Pool size |
| Deadline Exceeded Rate | < 0.1% | Deadline errors / Total requests |
| Serialization Time | < 5ms | Average serialization time |
Phase 1: Foundation (Weeks 1-2)
Phase 2: Integration (Weeks 3-4)
Phase 3: Optimization (Weeks 5-6)
Phase 4: Production (Weeks 7-8)
syntax = "proto3";
package user.v1;
import "google/protobuf/timestamp.proto";
service UserService {
// Unary RPC
rpc GetUser(GetUserRequest) returns (User);
// Server streaming RPC
rpc ListUsers(ListUsersRequest) returns (stream User);
// Client streaming RPC
rpc CreateUserBatch(stream CreateUserRequest) returns (CreateUserBatchResponse);
// Bidirectional streaming RPC
rpc UserEvents(stream UserEventRequest) returns (stream UserEventResponse);
}
message GetUserRequest {
string id = 1;
}
message User {
string id = 1;
string name = 2;
string email = 3;
google.protobuf.Timestamp created_at = 4;
}
message ListUsersRequest {
int32 page_size = 1;
string page_token = 2;
}
message CreateUserRequest {
string name = 1;
string email = 2;
}
message CreateUserBatchResponse {
repeated string user_ids = 1;
int32 created_count = 2;
}
message UserEventRequest {
string event_type = 1;
bytes payload = 2;
}
message UserEventResponse {
bool acknowledged = 1;
string message = 2;
}
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const { v4: uuidv4 } = require('uuid');
const PROTO_PATH = './proto/user_service.proto';
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const userProto = grpc.loadPackageDefinition(packageDefinition).user.v1;
const users = new Map();
const userService = {
getUser: (call, callback) => {
const user = users.get(call.request.getId());
if (!user) {
const error = new Error('User not found');
error.code = grpc.status.NOT_FOUND;
return callback(error);
}
callback(null, user);
},
createUser: (call, callback) => {
const user = {
id: uuidv4(),
name: call.request.getName(),
email: call.request.getEmail(),
createdAt: new Date(),
};
users.set(user.id, user);
callback(null, user);
},
listUsers: (call) => {
users.forEach(user => {
call.write(user);
});
call.end();
},
createUserBatch: (call, callback) => {
const userIds = [];
call.on('data', (request) => {
const user = {
id: uuidv4(),
name: request.getName(),
email: request.getEmail(),
createdAt: new Date(),
};
users.set(user.id, user);
userIds.push(user.id);
});
call.on('end', () => {
const response = new userProto.CreateUserBatchResponse();
response.setUserIdsList(userIds);
response.setCreatedCount(userIds.length);
callback(null, response);
});
},
userEvents: (call) => {
call.on('data', (request) => {
const response = new userProto.UserEventResponse();
response.setAcknowledged(true);
response.setMessage('Event received');
call.write(response);
});
call.on('end', () => {
call.end();
});
},
};
const server = new grpc.Server();
server.addService(userProto.UserService.service, userService);
server.bindAsync(
'0.0.0.0:50051',
grpc.ServerCredentials.createInsecure(),
(error, port) => {
if (error) {
console.error('Failed to start server:', error);
return;
}
console.log(`Server running on port ${port}`);
}
);
const grpc = require('@grpc/grpc-js');
const protoLoader = require('@grpc/proto-loader');
const PROTO_PATH = './proto/user_service.proto';
const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
keepCase: true,
longs: String,
enums: String,
defaults: true,
oneofs: true,
});
const userProto = grpc.loadPackageDefinition(packageDefinition).user.v1;
const client = new userProto.UserService(
'localhost:50051',
grpc.credentials.createInsecure()
);
// Unary call
function getUser(id) {
return new Promise((resolve, reject) => {
const request = new userProto.GetUserRequest();
request.setId(id);
client.getUser(request, (error, response) => {
if (error) {
return reject(error);
}
resolve(response.toObject());
});
});
}
// Create user
function createUser(name, email) {
return new Promise((resolve, reject) => {
const request = new userProto.CreateUserRequest();
request.setName(name);
request.setEmail(email);
client.createUser(request, (error, response) => {
if (error) {
return reject(error);
}
resolve(response.toObject());
});
});
}
// List users (server streaming)
function listUsers() {
return new Promise((resolve, reject) => {
const request = new userProto.ListUsersRequest();
const users = [];
const call = client.listUsers(request);
call.on('data', (user) => {
users.push(user.toObject());
});
call.on('end', () => {
resolve(users);
});
call.on('error', reject);
});
}
// Usage
(async () => {
try {
// Create user
const user = await createUser('John Doe', '[email protected]');
console.log('Created user:', user);
// Get user
const found = await getUser(user.id);
console.log('Found user:', found);
// List users
const allUsers = await listUsers();
console.log('All users:', allUsers);
} catch (error) {
console.error('Error:', error);
}
})();
const grpc = require('@grpc/grpc-js');
const jwt = require('jsonwebtoken');
const authInterceptor = (options, nextCall) => {
return new grpc.ServerInterceptingCall(nextCall(options), {
start: (metadata, listener, next) => {
const token = metadata.get('authorization')?.[0]?.replace('Bearer ', '');
if (!token) {
return next(null, {
status: { code: grpc.status.UNAUTHENTICATED, details: 'Missing token' },
});
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
options.user = decoded;
next(metadata, listener);
} catch (error) {
return next(null, {
status: { code: grpc.status.UNAUTHENTICATED, details: 'Invalid token' },
});
}
},
});
};
const server = new grpc.Server({
interceptors: [authInterceptor],
});
server.addService(userProto.UserService.service, userService);
const grpc = require('@grpc/grpc-js');
const fs = require('fs');
// Server with TLS
const serverCredentials = grpc.ServerCredentials.createSsl(
fs.readFileSync('ca.crt'), // CA certificate
[
{
cert_chain: fs.readFileSync('server.crt'),
private_key: fs.readFileSync('server.key'),
},
],
false // check client certificate
);
server.bindAsync(
'0.0.0.0:50051',
serverCredentials,
(error, port) => {
if (error) {
console.error('Failed to start server:', error);
return;
}
console.log(`Secure server running on port ${port}`);
}
);
// Client with TLS
const clientCredentials = grpc.credentials.createSsl(
fs.readFileSync('ca.crt'),
fs.readFileSync('client.key'),
fs.readFileSync('client.crt')
);
const client = new userProto.UserService(
'localhost:50051',
clientCredentials
);
// Client deadline
const deadline = new Date();
deadline.setSeconds(deadline.getSeconds() + 5); // 5 second deadline
client.getUser(request, { deadline }, (error, response) => {
if (error && error.code === grpc.status.DEADLINE_EXCEEDED) {
console.error('Request timed out');
}
});
// Server handling deadline
function getUser(call, callback) {
if (call.getDeadline().getTime() < Date.now()) {
const error = new Error('Deadline exceeded');
error.code = grpc.status.DEADLINE_EXCEEDED;
return callback(error);
}
// Process request...
}
const client = new userProto.UserService(
'dns:///user-service:50051', // DNS-based service discovery
grpc.credentials.createInsecure(),
{
'grpc.load_balancing_config': [
{ round_robin: {} },
],
}
);
const healthStatus = {
'': grpc.status.OK,
'user-service': grpc.status.OK,
};
const healthImpl = {
check: (call, callback) => {
const service = call.request.getService();
const status = healthStatus[service] || grpc.status.SERVICE_UNKNOWN;
const response = new healthProto.HealthCheckResponse();
response.setStatus(status);
callback(null, response);
},
watch: (call) => {
const service = call.request.getService();
const interval = setInterval(() => {
const status = healthStatus[service] || grpc.status.SERVICE_UNKNOWN;
const response = new healthProto.HealthCheckResponse();
response.setStatus(status);
call.write(response);
}, 1000);
call.on('cancelled', () => {
clearInterval(interval);
call.end();
});
},
};
server.addService(healthProto.Health.service, healthImpl);
xiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience