xiaohongshu
xiaohongshu
kv-store-grpc
Guidance for building gRPC-based key-value store services in Python. This skill should be used when tasks involve creating gRPC servers, defining protocol buffer schemas, or implementing key-value storage APIs with gRPC. Covers proto file creation, code generation, server implementation, and veri...
Full skill instructions
This skill provides procedural knowledge for implementing gRPC-based key-value store services in Python. It covers the complete workflow from proto file definition through server implementation and verification.
Install the required gRPC packages with specific versions if provided:
pip install grpcio==<version> grpcio-tools==<version>
If no versions are specified, install the latest:
pip install grpcio grpcio-tools
Verification: Run pip show grpcio grpcio-tools to confirm installation.
Create a .proto file defining the service and messages.
Key elements to include:
syntax = "proto3"; declarationpackage declaration (best practice for larger projects)Common proto patterns for key-value stores:
syntax = "proto3";
package kvstore;
service KVStore {
rpc SetVal(SetRequest) returns (SetResponse);
rpc GetVal(GetRequest) returns (GetResponse);
}
message SetRequest {
string key = 1;
int32 value = 2;
}
message SetResponse {
bool success = 1;
}
message GetRequest {
string key = 1;
}
message GetResponse {
int32 value = 1;
}
Common pitfall: Forgetting the package declaration - while not strictly required, it prevents naming conflicts in larger projects.
Run the protobuf compiler to generate Python code:
python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. <service_name>.proto
This generates two files:
<service_name>_pb2.py - Message classes<service_name>_pb2_grpc.py - Service stubs and base classesVerification: Confirm both files exist and contain the expected classes by reading them.
Important: Examine the generated *_pb2_grpc.py file to understand:
Create a server file that:
Key implementation details:
import grpc
from concurrent import futures
import <service_name>_pb2
import <service_name>_pb2_grpc
class KVStoreServicer(<service_name>_pb2_grpc.<ServiceName>Servicer):
def __init__(self):
self.store = {}
def SetVal(self, request, context):
self.store[request.key] = request.value
return <service_name>_pb2.SetResponse(success=True)
def GetVal(self, request, context):
value = self.store.get(request.key, 0) # Default to 0 for missing keys
return <service_name>_pb2.GetResponse(value=value)
def serve():
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
<service_name>_pb2_grpc.add_<ServiceName>Servicer_to_server(
KVStoreServicer(), server
)
server.add_insecure_port('[::]:50051')
server.start()
print("Server started on port 50051", flush=True) # flush=True is important!
server.wait_for_termination()
if __name__ == '__main__':
serve()
Critical pitfall - Output buffering: When running the server in the background, Python buffers stdout by default. To see output:
print(..., flush=True) for all print statements-u flag: python -u server.pylogging module instead of printRun the server in the background:
python server.py &
Or with unbuffered output:
python -u server.py &
Preferred approach: Write and run a test client. This is more reliable than system tools.
Common mistake: Attempting to use system tools like netstat, ss, lsof, or ps to verify the server. These tools may not be available in all environments. Instead, test the server directly with a client.
Test client template:
import grpc
import <service_name>_pb2
import <service_name>_pb2_grpc
def test_kv_store():
channel = grpc.insecure_channel('localhost:50051')
stub = <service_name>_pb2_grpc.<ServiceName>Stub(channel)
# Test SetVal
set_response = stub.SetVal(<service_name>_pb2.SetRequest(key="test_key", value=42))
print(f"SetVal response: success={set_response.success}")
# Test GetVal
get_response = stub.GetVal(<service_name>_pb2.GetRequest(key="test_key"))
print(f"GetVal response: value={get_response.value}")
# Test non-existent key (should return default value)
get_missing = stub.GetVal(<service_name>_pb2.GetRequest(key="missing_key"))
print(f"GetVal missing key: value={get_missing.value}")
if __name__ == '__main__':
test_kv_store()
Comprehensive testing should verify:
| Pitfall | Solution |
|---|---|
| Print statements not appearing when server runs in background | Use flush=True or run with python -u |
| Trying to use netstat/ss/lsof to verify server | Write a test client instead - more reliable |
| Missing package declaration in proto | Add package <name>; after syntax declaration |
| Not examining generated code before implementing | Read *_pb2_grpc.py to understand the servicer interface |
| Incomplete verification | Test all operations including edge cases |
| No default value for missing keys | Use dict.get(key, default) pattern |
*_pb2_grpc.py file before implementing to understand method signaturesxiaohongshu
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