Fix SAP Business One Service Layer 'Invalid session' (code 301)
SAP Business One Service Layer Invalid session or session already timed out
Also searched as
- SAP B1 Service Layer error 301 invalid session
- B1SESSION cookie expired Service Layer
- Service Layer Login session timeout 30 minutes
- SAP Business One Service Layer ROUTEID cookie load balancer
Short answer
The Service Layer returns code 301 'Invalid session or session already timed out' when the B1SESSION cookie you send no longer maps to a live session. The usual causes are the default idle timeout (30 minutes), a missing or altered cookie, a load balancer sending the call to a different node because ROUTEID was dropped, or a restarted Service Layer. Fix it by keeping cookies on every call and re-logging in once on a 301.
Applies to: SAP Business One 9.3, 10.0 and later, on SQL Server and SAP HANA, Service Layer v1 and v2 (OData)
How to fix the invalid session error
- 1Confirm the failing call is not the Login itself: POST /b1s/v1/Login with CompanyDB, UserName and Password should return a SessionId and set the B1SESSION cookie.
- 2Check that your HTTP client stores and resends cookies. Use a cookie jar (curl -b/-c, requests.Session, HttpClient with CookieContainer). Sending only the SessionId in the body does nothing.
- 3If a load balancer or reverse proxy sits in front, make sure it passes both B1SESSION and ROUTEID. ROUTEID pins the call to the node that holds the session.
- 4Measure idle time between calls. If it can exceed the session timeout (30 minutes by default), either ping a cheap endpoint on a schedule or accept the timeout and relogin.
- 5Add retry logic: on HTTP 401 or error code 301, call Login once, replace the cookies, and replay the failed request. Do not loop more than once.
- 6Logout explicitly (POST /b1s/v1/Logout) when a batch job ends, so abandoned sessions do not consume licences or connection slots.
- 7If the error appears right after a service restart or patch, restart the client so it discards the stale cookie, then log in fresh.
What the session actually is
A Service Layer login creates a server-side session tied to the company database, the B1 user and a licence. The B1SESSION cookie is the key to it. When the session expires or the Service Layer process restarts, the key points at nothing, and every later call returns the invalid session error.
The error body looks like this: an error object with code 301 and a message value of 'Invalid session or session already timed out.' Some stacks surface it as HTTP 401, others as 400, so key your retry logic on the error code in the body as well as the status.
Sessions also consume a B1 licence while they are open. A script that logs in per request and never logs out will exhaust licences or connection limits long before it hits any timeout, and that shows up as login failures rather than 301.
POST https://sapb1:50000/b1s/v1/Login
{"CompanyDB":"SBODEMOUS","UserName":"manager","Password":"***"}
HTTP/1.1 200 OK
Set-Cookie: B1SESSION=...; path=/b1s
Set-Cookie: ROUTEID=.node1; path=/b1s
GET /b1s/v1/Items('A00001')
Cookie: B1SESSION=...; ROUTEID=.node1Timeout, keep-alive and relogin
The default idle timeout is 30 minutes and it is configurable in the Service Layer configuration on the server. Raising it is a legitimate fix for a long-running integration, but a very long timeout leaves sessions open after a crashed client, so prefer a bounded value plus relogin.
Each authenticated call resets the idle timer. A lightweight request, such as reading a single small record, is enough as a keep-alive. Do not use a heavy query for this.
The most robust pattern is the reactive one. Wrap every call in a function that catches code 301, performs one Login, and retries. Combined with a cookie jar per worker, this survives timeouts, restarts and failovers without special cases.
Load balancers and ROUTEID
In a multi-node Service Layer deployment, the built-in Apache-based balancer adds a ROUTEID cookie so that follow-up calls reach the node holding your session. If a reverse proxy, API gateway or integration platform strips or does not forward that cookie, requests are spread across nodes and some hit a node that never saw your login. That produces intermittent 301 errors that seem random.
Test by calling the same endpoint repeatedly with curl using a cookie jar, then once without ROUTEID. If only the second fails sometimes, the proxy is the cause. Configure the proxy to forward both cookies, or use sticky sessions at that layer.
Concurrency and session pools
A single session is not designed for heavy parallel use. Create a small pool of sessions, for example one per worker thread, and reuse each for many calls. Logging in for every request is slow, and one shared session across many threads can serialize or fail unpredictably.
Keep the pool small. Each session takes a licence, and the licence type of the B1 user matters: indirect access and professional users are counted differently, so agree this with your SAP partner before sizing the pool.
Common pitfalls
- !Treating the SessionId in the login response body as the credential. The cookie is what the server checks.
- !Dropping ROUTEID in a proxy or API gateway, causing intermittent 301 errors only in multi-node setups.
- !Logging in per request and never logging out, which exhausts licences and looks like a login problem.
- !Retrying forever on 301. If a fresh login also fails, the problem is credentials, licence or company database, not the session.
- !Sharing one session across many threads and then blaming the Service Layer for sporadic failures.
- !Setting an extreme timeout to hide a client that does not handle relogin.
How an ERP-grounded AI assistant handles this
An assistant grounded in SAP Business One, such as ERPray, usually does not hold a long-lived Service Layer session at all. It reads through a read-only connection or a short-lived, pooled session, shows the query it ran, and respects the B1 user's authorizations. For write-back, such as creating a document through the Service Layer, a human approves the payload first. When you are debugging this error, an assistant can read your integration logs and the response headers you paste in and point at the missing cookie or the timeout window.
Frequently asked questions
What is the default Service Layer session timeout?
It is 30 minutes of idle time by default. Every authenticated call resets the timer. The value is set in the Service Layer configuration on the server, so an administrator can raise or lower it, but a handler that relogs in on code 301 is more robust than a long timeout.
Do I need to send the SessionId from the login response?
No. Standard clients rely on the B1SESSION cookie set by the login response. The SessionId in the body is informational for most uses. If your client does not persist cookies, every call after login will fail with an invalid session error.
Why do I get 301 only some of the time?
Intermittent 301 errors almost always mean multiple Service Layer nodes behind a balancer without the ROUTEID cookie being forwarded, or several workers sharing one cookie jar. Capture the request headers of a failing call and check both B1SESSION and ROUTEID are present.
Should I log out after every batch?
Yes. Call POST /b1s/v1/Logout when a job finishes. Open sessions use licences and server resources until they time out, and a scheduled job that forgets to log out can leave dozens of idle sessions behind.
Related
SAP Business One: Posting Date Blocked by a Locked Period
When SAP Business One reports that the posting date deviates from the permissible range, the date falls in a posting period that is locked or in a sub-period that does not allow that type of posting. Check Administration > System Initialization > Posting Periods, confirm the period status and sub-period, and have an authorized user change it, or move the document to a date in an open period.
Error fixFix SAP Business One 'Quantity falls below zero' (-2028) on Production Issue
SAP Business One raises 'Quantity falls below zero' (ODBC -2028) when a goods issue, including an Issue for Production, would push an item's on-hand quantity in a warehouse, or a batch or serial, below zero and negative inventory is not allowed. Fix it by receiving the stock first, correcting the warehouse or batch, or deliberately allowing negative stock for the right items.
How-toHow to Use BAPI_TRANSACTION_COMMIT Correctly
SAP's BAPI programming model separates business logic from the database commit on purpose, so a caller must explicitly call BAPI_TRANSACTION_COMMIT after a successful BAPI - usually with WAIT = 'X' - or the created object never actually persists. Skipping this step, or forgetting WAIT, is the most common reason a BAPI 'runs fine' but nothing gets saved.
Error fixSAP M7 021: Deficit of SL Stock Quantity
M7 021 fires during a goods issue, delivery, or confirmation when SAP checks the unrestricted-use (SL) stock for the exact plant, storage location and batch combination and finds less than what you are trying to post out. Fix the entry (batch, storage location, quantity) first; only enable negative stock or downgrade the message to a warning if the business genuinely needs to post ahead of a receipt.
Error fixSAP IDoc Status 51: Application Document Not Posted
Status 51 tells you the IDoc reached the application layer and failed to post, but the status text itself is not the error - the real cause sits in the status record's long text or the linked application log. Fix the underlying data or configuration, then reprocess the IDoc through BD87 rather than editing the status.
Error fixSAP Short Dump TIME_OUT: Maximum Runtime Exceeded
A TIME_OUT runtime error means a dialog (or RFC) work process ran longer than the maximum allowed runtime, controlled by profile parameter rdisp/max_wprun_time (600 seconds by default). The fix is almost always to move the long-running work to background processing or tune the underlying program, not to raise the timeout.
AI for ERPAI for SAP Business One, Without Sending Your Books to a Public API
Add AI to SAP Business One without sending customer data or financials to a public API. Service Layer and DI API integration, sized for an SMB budget.
AI for ERPAI Agents for SAP Production Planning, MRP, and Exception Triage
AI agents that triage SAP MD04 exceptions, explain predictive MRP shortages, and draft planned-order actions, grounded on your own SAP data, deployed on-prem.
Stuck on SAP Business One?
Talk to engineers who work inside SAP Business One every week, and who build private AI that answers these questions from your own ERP data.