mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-03 21:18:19 +07:00
[GH-ISSUE #6023] [Bug/Improvement]: PostgreSQL outage causes misleading startup error, unlimited restart loop, and massive log growth #4171
Labels
No labels
backlog
bug
clarification needed
documentation
duplicate
enhancement
github_actions
good first issue
invalid
javascript
New Feature
PR welcomed
pull-request
question
wontfix
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
MHSanaei/3x-ui#4171
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Originally created by @z2roozsh on GitHub (Jul 18, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6023
Describe the bug
Summary
When 3X-UI is configured to use PostgreSQL and the database becomes temporarily unavailable, the panel exits immediately. The systemd service then restarts it every five seconds without an effective restart limit.
The
x-uimanagement script reports only:In my case, the problem was not that startup required more than two seconds. The process exited almost immediately because PostgreSQL had crashed after the server filesystem became full.
Because the actual database error was not shown by the script, troubleshooting became unnecessarily difficult. At the same time, the automatic restart loop generated a very large number of log entries and made the disk-space problem worse.
I am reporting the full incident and recovery process so the installer, management script, systemd unit, and possibly the application itself can handle this failure mode more safely.
Environment
3.5.026.7.1116.14127.0.0.1:5433xui/etc/systemd/system/x-ui.service/etc/default/x-uiSensitive database credentials, public IP addresses, usernames, and hostnames have been removed from this report.
Initial user-visible behavior
The management menu showed:
Selecting Start produced:
Restarting produced:
This message suggested a startup timing problem, but the service was actually exiting with status 1 almost immediately.
Actual service failure
systemctl status x-uishowed:The real error appeared only after manually running:
The relevant message was:
At other times during the incident, the database error was:
The panel could not initialize its database and exited. Xray therefore did not start under the x-ui service.
Root cause
The root filesystem had reached 100% usage:
PostgreSQL attempted a checkpoint and failed:
PostgreSQL then terminated its server processes and entered automatic crash recovery:
While PostgreSQL was unavailable, x-ui continued restarting every five seconds because the service contained:
There was no practical restart burst limit in the service configuration.
The restart counter reached at least:
Log amplification
The full filesystem had multiple contributors, including SSH brute-force records and another verbose service. However, x-ui’s failure loop significantly amplified the incident.
The largest logs included:
When I counted program names in
kern.log, I found:In other words, more than four million entries in
kern.logwere attributed to the x-ui executable.The default rsyslog configuration was normal:
This means x-ui’s userspace messages appear to have been submitted with a kernel syslog facility, or otherwise classified as
kern.*.Example entries found in
kern.log:A userspace panel process should not normally generate millions of entries in the kernel log.
PostgreSQL status was also misleading
On Debian/Ubuntu, this command showed:
That wrapper unit looked healthy even though the actual PostgreSQL cluster was stuck.
The relevant unit was:
It showed:
The PostgreSQL process list contained a stuck cluster process and checkpointer.
Therefore, checking only
postgresql.serviceis insufficient on Debian-based systems. Diagnostics should identify the actual cluster unit, for example throughpg_lsclusters.Recovery steps used
1. Stop the x-ui restart loop
I temporarily masked the service:
This stopped further restart attempts without permanently disabling autostart.
2. Free disk space
I identified the largest logs and cleared the accumulated files after preserving diagnostic samples.
After cleanup:
3. Stop the stuck PostgreSQL cluster
A normal stop did not complete:
The cluster remained in
deactivatingstate for more than 15 minutes.An immediate PostgreSQL shutdown signal was then sent through systemd:
This is an emergency recovery action, not something that should normally be required.
PostgreSQL then performed automatic crash recovery:
4. Verify PostgreSQL
Result:
Recovery status:
Result:
5. Start x-ui again
The service then started successfully:
The management menu finally showed:
No database restoration was required, and no database corruption was detected after recovery.
Problems in the current behavior
1. The two-second check produces a misleading diagnosis
The current start/restart flow effectively performs:
If the process is not running, it says that startup probably took longer than two seconds.
This does not distinguish between:
In this incident, the process had already exited. Waiting longer would never have fixed it.
2. The real error is hidden
The management script tells the user to check logs later but does not print the relevant logs or provide the exact command.
Many users will not know to run:
The script already has enough context to display these automatically.
3. Unlimited automatic retries create a log storm
A five-second restart interval without an effective burst limit means approximately:
A persistent dependency failure can therefore create enormous logs and unnecessary CPU/process churn.
4. PostgreSQL dependency health is not checked
If the configured backend is PostgreSQL, the management script does not appear to check whether the configured PostgreSQL endpoint is reachable before starting the panel.
It also does not recognize common PostgreSQL states such as:
5. The database wrapper service can give a false healthy result
On Ubuntu,
postgresql.serviceis a wrapper and may reportactive (exited)while the real cluster is unhealthy.The script should inspect:
when using a local PostgreSQL installation.
6. x-ui messages were written into
kern.logMore than four million x-ui messages were present in
/var/log/kern.log.The application’s syslog facility should be reviewed. Userspace application logs should use an appropriate facility such as:
daemon;user;local0;They should not be classified as kernel messages.
7. Global Xray process detection may be inaccurate
The script appears to determine Xray status by globally searching for an
xray-linuxprocess.On servers where another panel or service also runs Xray, this can report:
even if the Xray instance belonging to 3X-UI is not running.
Xray status should be scoped to:
Suggested improvements
A. Replace the fixed two-second sleep with a bounded service-state loop
Example logic:
The result could distinguish:
0: started successfully;1: exited or failed;2: still activating after timeout.B. Print immediate diagnostics on failure
When start or restart fails, automatically show:
The output should preferably be filtered to the current boot or current invocation:
The script should print the actual
ExecMainStatusand service result:Example user-facing output:
C. Add PostgreSQL preflight diagnostics
When
XUI_DB_TYPE=postgres, the script should read the configured DSN from the environment file and test the database host and port without printing the password.Possible checks:
If
pg_isreadyis unavailable, a TCP connectivity test could be used as a fallback.The script should not log the full DSN because it contains credentials.
Recognized error states should include:
D. Detect disk exhaustion automatically
When PostgreSQL or x-ui fails, the diagnostic routine should run:
If any relevant filesystem is near capacity, show a prominent warning:
It could also search recent PostgreSQL logs for:
E. Inspect the real PostgreSQL cluster on Debian/Ubuntu
For a locally installed PostgreSQL server:
Then inspect the actual cluster service:
Do not rely only on:
because that unit may be
active (exited)while a cluster is unavailable.F. Stop automatic retries when a persistent dependency failure is detected
The script could stop the service after detecting a PostgreSQL failure:
It should tell the user that x-ui was stopped to prevent a restart/log loop.
A temporary runtime mask could optionally be offered:
This should not be applied silently, but it could be presented as an interactive recovery option.
G. Add systemd restart limits
A safer service configuration would include something similar to:
This allows recovery from temporary failures but prevents indefinite five-second loops.
Another option is exponential or progressively increasing restart backoff if supported by the target systemd versions.
H. Add application-level database retry/backoff
Instead of exiting immediately after one failed connection, the backend could retry PostgreSQL initialization with bounded exponential backoff.
Example behavior:
After a reasonable timeout, it could exit with one clear final error.
This would avoid hundreds of complete process restarts for a short PostgreSQL recovery.
I. Correct the logging facility
Please audit how x-ui submits logs to syslog/journald.
Messages such as:
should not be written with the
kernfacility.Recommended behavior:
J. Add an
x-ui doctorcommandA diagnostic command could test:
Example:
Possible output:
K. Scope Xray status to the x-ui service
Instead of a global process search, use a service-scoped check such as:
Or track the exact Xray child process started by the panel.
This avoids reporting another application’s Xray process as the 3X-UI Xray process.
Expected behavior
When the panel fails because PostgreSQL is unavailable, the management script should provide an actionable message such as:
It should not describe this situation as probably taking longer than two seconds.
Proposed acceptance criteria
57P03produces a database-specific explanation.kern.log.Final result after manual recovery
After freeing disk space, recovering PostgreSQL, and restarting x-ui:
The panel, subscription server, and Xray core all started successfully.
This incident was ultimately recoverable, but the management script’s generic message and the unbounded restart loop made the failure much harder to diagnose and significantly increased log volume. Better dependency diagnostics and restart controls would make this class of incident much safer for other users.
How to reproduce the problem
Actual service failure
systemctl status x-ui showed:
Active: activating (auto-restart) (Result: exit-code)
Process: ... ExecStart=/usr/local/x-ui/x-ui (code=exited, status=1/FAILURE)
Main PID: ... (code=exited, status=1/FAILURE)
The real error appeared only after manually running:
journalctl -u x-ui -n 100 --no-pager
The relevant message was:
Starting x-ui 3.5.0
Error initializing database:
failed to connect to
user=[REDACTED] database=xui:127.0.0.1:5433:
FATAL: the database system is in recovery mode
(SQLSTATE 57P03)
At other times during the incident, the database error was:
FATAL: the database system is shutting down
(SQLSTATE 57P03)
The panel could not initialize its database and exited. Xray therefore did not start under the x-ui service.
Root cause
The root filesystem had reached 100% usage:
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 19G 19G 0 100% /
PostgreSQL attempted a checkpoint and failed:
PANIC: could not write to file
"pg_logical/replorigin_checkpoint.tmp":
No space left on device
PostgreSQL then terminated its server processes and entered automatic crash recovery:
checkpointer process was terminated by signal 6: Aborted
terminating any other active server processes
database system was not properly shut down
automatic recovery in progress
While PostgreSQL was unavailable, x-ui continued restarting every five seconds because the service contained:
Restart=on-failure
RestartSec=5s
There was no practical restart burst limit in the service configuration.
The restart counter reached at least:
restart counter is at 130
Log amplification
The full filesystem had multiple contributors, including SSH brute-force records and another verbose service. However, x-ui’s failure loop significantly amplified the incident.
The largest logs included:
772M /var/log/kern.log
275M /var/log/syslog
269M /var/log/btmp
244M /var/log/auth.log
When I counted program names in kern.log, I found:
4023499 /usr/local/x-ui/x-ui
3795 kernel
In other words, more than four million entries in kern.log were attributed to the x-ui executable.
The default rsyslog configuration was normal:
.;auth,authpriv.none -/var/log/syslog
kern.* -/var/log/kern.log
This means x-ui’s userspace messages appear to have been submitted with a kernel syslog facility, or otherwise classified as kern.*.
Example entries found in kern.log:
/usr/local/x-ui/x-ui[PID]: INFO - GC percent set to 75
/usr/local/x-ui/x-ui[PID]: INFO - Go memory soft limit not enforced
A userspace panel process should not normally generate millions of entries in the kernel log.
PostgreSQL status was also misleading
On Debian/Ubuntu, this command showed:
systemctl status postgresql
postgresql.service - PostgreSQL RDBMS
Active: active (exited)
That wrapper unit looked healthy even though the actual PostgreSQL cluster was stuck.
The relevant unit was:
systemctl status postgresql@16-main
It showed:
Active: deactivating (stop-sigterm) (Result: exit-code)
The PostgreSQL process list contained a stuck cluster process and checkpointer.
Therefore, checking only postgresql.service is insufficient on Debian-based systems. Diagnostics should identify the actual cluster unit, for example through pg_lsclusters.
Expected behavior
No response
Actual behavior
Initial user-visible behavior
The management menu showed:
Panel state: Not Running
Start automatically: Yes
xray state: Not Running
Selecting Start produced:
[ERR] panel Failed to start, Probably because it takes longer than two seconds to start, Please check the log information later
Restarting produced:
[ERR] Panel restart failed, Probably because it takes longer than two seconds to start, Please check the log information later
This message suggested a startup timing problem, but the service was actually exiting with status 1 almost immediately.
Relevant logs
Screenshots
No response
3x-ui version
3.5.0
Xray-core version
No response
How did you install 3x-ui?
install.sh script
Operating system
linux ubuntu 22
Which parts of the panel are affected?
No response
Browser (only if it is a UI bug)
No response
Is the panel behind a reverse proxy or CDN?
None
Before submitting
@github-actions[bot] commented on GitHub (Jul 18, 2026):
Investigated against
v3.5.0(current latest release, and nothing since addresses this). The report is accurate; two items are confirmed defects with a clear root cause, and the rest are legitimate gaps rather than bugs in existing behavior. Details below, each grounded in the file and line checked.Title: Syslog backend logs everything under the kernel facility, so panel output lands in
kern.logSeverity: Medium
Category: Correctness
Why this matters:
internal/logger/logger.go:85callslogging.NewSyslogBackend("")from the pinned dependencygithub.com/op/go-logging v0.0.0-20160315200505-970db520ece7(go.mod:18). The implementation ofNewSyslogBackendissyslog.New(syslog.LOG_CRIT, prefix), andLOG_CRITis a severity-only constant with no facility bits set. In the stdliblog/syslogpackage (writeAndRetry:pr := (w.priority & facilityMask) | (p & severityMask)), the facility of every subsequent write comes from the priority passed toNew(); with no facility bits set, that defaults toLOG_KERN(facility 0). So every line the panel logs, Info, Warning, Error, all of it, is submitted to the local syslog socket tagged as a kernel message, independent of its real severity. Against the default Debian/Ubuntu rsyslog rule quoted in this report (kern.* -/var/log/kern.log), that routes the entire log output of the panel intokern.log. This matches the report precisely: theINFO - GC percent set to 75/INFO - Go memory soft limit not enforcedlines found inkern.logcome fromlogger.Info(line)inmain.go:56-58(fed bysys.ApplyMemoryTuning()), which goes through this backend, while theError initializing database: ...message that only showed up injournalctl -u x-uiis printed via the stdliblog.Fatalfatmain.go:71, which bypasses this backend and goes straight to stderr/journal. Nothing here is Docker- or install-method-specific; any systemd/local-syslog install with a default rsyslog config is affected.Recommendation: pass an explicit non-kernel facility. The same dependency also exports
NewSyslogBackendPriority(prefix string, priority syslog.Priority), soinitDefaultBackend(internal/logger/logger.go:75-95) could call it with asyslog.LOG_DAEMON-based priority instead ofNewSyslogBackend(""). A fix will only be made if a maintainer requests it by mentioning @claude.Title: Shipped systemd units have no effective restart-attempt limit
Severity: Medium
Category: Reliability
Why this matters:
x-ui.service.debian,x-ui.service.rhel, andx-ui.service.archall setRestart=on-failure/RestartSec=5sand none setStartLimitIntervalSec=/StartLimitBurst=in[Unit]. The documented systemd default start-limit window (DefaultStartLimitIntervalSec=10s,DefaultStartLimitBurst=5, fromsystemd-system.conf) is what would normally stop a crash-looping unit, but at a fixed 5-secondRestartSeconly about two start attempts fall inside any rolling 10-second window, never reaching the default burst of 5, so the unit is never placed intostart-limit-hitand restarts indefinitely. That lines up with the reported "restart counter is at 130" while the service stayed inactivating (auto-restart). This is independent of the application: even a non-transient failure such as a bad DSN or missing credentials will restart every 5 seconds forever.Recommendation: add explicit
StartLimitIntervalSec=/StartLimitBurst=to[Unit]in the threex-ui.service.*files, as suggestion G in the report proposes. A fix will only be made if a maintainer requests it by mentioning @claude.Also confirmed directly against the source (accurate gaps, not defects, enhancement territory, corresponding to suggestions A-D, H, J, K in the report):
start()/restart()inx-ui.sh(lines 493-597) runsystemctl start|restart x-ui,sleep 2, thencheck_status, and print that fixed string (x-ui.sh:518,:592) whenevercheck_statusdoes not seerunning.check_status(x-ui.sh:863-894) only greps theActiveline for the wordrunning; it never readsExecMainStatus/Result, so "still starting", "exited immediately", and "crash-looping" are indistinguishable to the script.LOGEcalls in those same functions never invokejournalctl/systemctl status.x-ui.sh, and no SQLSTATE-aware handling in the Go startup path; a search forSQLSTATE/57P03/pgconnacrossinternal/turns up only one unrelated hit, a deadlock-retry comment ininternal/web/service/traffic_writer.go:120.x-ui.sh(suggestion D).database.InitDB(internal/database/db.go:1750) returns the raw driver error on the first failure, andmain.go:69-71callslog.Fatalfimmediately; there is no retry/backoff before the process exits (suggestion H).check_xray_status()(x-ui.sh:973-980) runs an unscopedps -ef | grep "xray-linux", with no PID file, cgroup, or parent-PID scoping (suggestion K).x-ui doctoror equivalent diagnostic subcommand; the CLI only definesrun,migrate,migrate-db,setting, andcert(main.go:593-679, suggestion J).postgresql.servicewrapper andpostgresql@<version>-<cluster>(suggestion E) is accurate general behavior of thepostgresql-commonpackaging used on Debian/Ubuntu, not something in this repository; worth acting on, but outside the current scope ofx-ui.sh.3xuiandpostgresservices indocker-compose.ymlhave nodepends_on/healthcheck coupling, andrestart: unless-stoppedhas no burst limiting either.Given this bundles a couple of confirmed defects with a larger set of reasonable reliability and tooling requests, the
buglabel stays andenhancementis being added.Fixes are not applied here; this is a read-only triage pass. @MHSanaei for visibility and to decide on scope and priority, since addressing this touches the install script, all three systemd unit files, and the Go startup/logging path.
This reply was generated automatically by an AI agent. A maintainer may follow up.
@MHSanaei commented on GitHub (Jul 23, 2026):
Fixed in #6083. The initial PostgreSQL connection now retries with backoff and logs the real error, and the systemd units carry StartLimit* so an unreachable DB stops the unit instead of looping.